最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Resizing a HTML canvas blanks its contents - Stack Overflow

programmeradmin0浏览0评论

I have a HTML canvas element which is resized when the user resizes the screen.

canvas.height = pageHeight();
canvas.width = pageWidth();

The actual resizing works fine, but it blanks the canvas.

I would like to keep the contents. Is there another method of changing the size of a canvas element, or is there a way to store the contents and then draw them back to the canvas?

I have a HTML canvas element which is resized when the user resizes the screen.

canvas.height = pageHeight();
canvas.width = pageWidth();

The actual resizing works fine, but it blanks the canvas.

I would like to keep the contents. Is there another method of changing the size of a canvas element, or is there a way to store the contents and then draw them back to the canvas?

Share Improve this question asked Aug 22, 2010 at 20:56 Richard GarsideRichard Garside 89.2k12 gold badges87 silver badges97 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

You need to either resize the canvas with CSS or redraw the canvas after you resize it.

If you want to save the content of the canvas and redraw it, I can think of a few options:

  1. Use context.getImageData to grab the whole canvas, resize the canvas, then use context.putImageData to redraw it at the new scale.
  2. Create an Image object, setting the source to the result of canvas.toDataUrl(), resize the canvas, then draw the image at the new scale.
  3. call context.setScale(xscale, yscale) and call whatever function you used to draw the canvas originally. Assuming you set up xscale and yscale correctly, it will automatically scale everything to the new size.
  4. Create a new canvas with the updated size and call context.drawImage(oldCanvas, ...) to copy the old canvas onto the new one. Then you would switch out the old canvas with the new one.

The first two options won't work if you have drawn an image from a different domain to the canvas at any time, and aren't supported by older implementations.

In my opinion, option 3 (redrawing the image at the new scale) is the best if it's possible. It's the only option that will keep your lines completely smooth and sharp, and it will always work (assuming you still have all the information to generate the image).

发布评论

评论列表(0)

  1. 暂无评论