调整HTML画布的大小会使其内容空白 [英] Resizing a HTML canvas blanks its contents

查看:647
本文介绍了调整HTML画布的大小会使其内容空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML画布元素,当用户调整屏幕大小时调整大小。

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.

我想保留内容。是否有另一种方法来改变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?

推荐答案

您需要使用CSS调整画布大小或在重新调整大小后重新绘制画布。

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. 使用 context.getImageData 要抓取整个画布,调整画布大小,然后使用 context.putImageData 以新比例重新绘制。

  2. 创建 Image 对象,将源设置为 canvas.toDataUrl()的结果,调整画布大小,

  3. 调用 context.setScale(xscale,yscale)并调用您最初用于绘制画布的任何函数。假设您正确设置了 xscale yscale ,它会自动将所有内容缩放为新尺寸。

  4. 使用更新的大小创建一个新画布,并调用 context.drawImage(oldCanvas,...)将旧画布复制到新画布上。

  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.

在我看来,选项3(以新的比例重新绘制图像)在任何时候都是从不同的域到画布,是最好的,如果它的可能。这是唯一的选项,将保持你的线完全平滑和锐利,它将始终工作(假设你仍然有所有的信息,以生成图像)。

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).

这篇关于调整HTML画布的大小会使其内容空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆