HTML canvas - 绘制在调整大小时消失 [英] HTML canvas - drawing disappear on resizing

查看:1221
本文介绍了HTML canvas - 绘制在调整大小时消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML canvas元素中创建了一个基本形状,它工作正常。

I have created a basic shape in HTML canvas element which works fine.

当我调整画布大小时,出现问题,画布中的所有绘图都消失了。这是正常的行为吗?或者有一个功能,可以用来停止这个?

The problem occurs when I resize the canvas, all the drawing in the canvas disappears. Is this the normal behavior? or is there a function that can be used to stop this?

解决这个问题的一种方法是在canvas尺寸上调整绘图函数,但是如果要绘制大量内容,这可能不是很有效。

One way to fix this could be to call drawing function again on canvas resize however this may not be very efficient if there is huge content to be drawn.

最好的方法是什么?

这是指向示例代码的链接 https://gist.github.com/2983915

Here is the link to sample code https://gist.github.com/2983915

推荐答案

您需要重绘

设置画布的宽度或高度,即使您将其设置为与之前相同的值不仅清除画布,而且重置整个画布上下文。任何设置的属性( fillStyle lineWidth ,剪切区域等)也将重置。

setting the width or height of a canvas, even if you are setting it to the same value as before, not only clears the canvas but resets the entire canvas context. Any set properties (fillStyle, lineWidth, the clipping region, etc) will also be reset.

如果你不能从任何数据结构重绘画面,代表画布,你总是可以通过将整个画布绘制到内存画布来保存整个画布,设置原始宽度,并将内存中的画布绘制回原始画布。

If you do not have the ability to redraw the scene from whatever data structures you might have representing the canvas, you can always save the entire canvas itself by drawing it to an in-memory canvas, setting the original width, and drawing the in-memory canvas back to the original canvas.

这是一个非常快速的例子,保存画布位图并在调整大小后放回:

Here's a really quick example of saving the canvas bitmap and putting it back after a resize:

http://jsfiddle.net/simonsarris/weMbr/

这篇关于HTML canvas - 绘制在调整大小时消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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