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?Answer1:
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
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 <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-scale" rel="nofollow">
scale method</a> of the canvas object.
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
<a href="https://stackoverflow.com/questions/11265483/inconsistencies-when-transform-scale-on-iframe-containing-canvas" rel="nofollow">https://stackoverflow.com/questions/11265483/inconsistencies-when-transform-scale-on-iframe-containing-canvas</a>