3

I am working on an application that incorporates a drawing interface (like Paint or Photoshop) as an HTML5 canvas element.

I would like to be able to dynamically resize the canvas element and the pixel data on it to simulate zoom functionality. My thoughts are having some kind of a viewport which contains the canvas element. I could then resize the canvas and its contents inside of the viewport (which stays the same size).

How would I best implement this functionality?

Mark Brouch
  • 119
  • 1
  • 3
  • 9
  • You could save a 'screenshot' using `.toDataURL()`, then resize the canvas and draw that screenshot stretched. However, it will look blurry because canvas will not resize 'pixelatedly'. – pimvdb Aug 11 '11 at 21:51
  • possible duplicate: http://stackoverflow.com/questions/331052/how-to-resize-html-canvas-element – Anderson Green Dec 16 '12 at 20:10

2 Answers2

10

You can do this very easily by seperating the display from the drawing surface by introducing another canvas. Create a hidden canvas using

var canvas = document.createElement('canvas');

Then draw your entire scene to this canvas. Then draw the contents of this canvas to another canvas that is actually visible to the user using the drawImage method (which may also receive a canvas instead of an image). If you want to draw your scene zoomed in, you can do this by making the source rectangle (the sy, sx, sw and sh parameters on drawImage) on the hidden canvas smaller, when drawing it to the visual canvas. This will give you the zooming effect.

However, if you completely redraw each frame on your canvas anyway, you may also simply have a look at the scale method of the canvas object.

Daniel Baulig
  • 10,739
  • 6
  • 44
  • 43
  • I tried, but I don't think my account is capable of that yet. :( You still get the satisfaction of a job well done. :D – Mark Brouch Aug 12 '11 at 19:29
0

I'm having success using transform: scale() on a canvas element and its contents. However in situations where the canvas element needs to be brought in with an iframe and the transform: scale happens on the iframe it works on safari but not mobile safari. Relevant link below

https://stackoverflow.com/questions/11265483/inconsistencies-when-transform-scale-on-iframe-containing-canvas

Community
  • 1
  • 1
PrimeLens
  • 2,547
  • 4
  • 23
  • 28