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

查看:38
本文介绍了调整 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.

我想保留内容.有没有另一种改变画布元素大小的方法,或者有没有办法存储内容然后将它们绘制回画布?

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) 并调用您最初用来绘制画布的任何函数.假设您正确设置了 xscaleyscale,它会自动将所有内容缩放到新大小.
  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天全站免登陆