HTML 画布 - 调整大小时绘图消失 [英] HTML canvas - drawing disappear on resizing

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

问题描述

我在 HTML 画布元素中创建了一个基本形状,效果很好.

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?

解决此问题的一种方法是在画布调整大小时再次调用绘图函数,但是如果要绘制大量内容,这可能不是很有效.

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

推荐答案

调整大小时需要重新绘制场景.

You need to redraw the scene when you resize.

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

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 画布 - 调整大小时绘图消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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