admin管理员组

文章数量:1277273

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?

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?

Share Improve this question asked Aug 11, 2011 at 21:30 Mark BrouchMark Brouch 1191 gold badge3 silver badges9 bronze badges 2
  • 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 Commented Aug 11, 2011 at 21:51
  • possible duplicate: stackoverflow./questions/331052/… – Anderson Green Commented Dec 16, 2012 at 20:10
Add a ment  | 

2 Answers 2

Reset to default 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 pletely redraw each frame on your canvas anyway, you may also simply have a look at the scale method 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

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

本文标签: javascriptResize and scale HTML5 Canvas and contentsStack Overflow