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?
解决方案
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.