调整 HTML5 Canvas 和内容的大小和比例
我正在开发一个应用程序,它将绘图界面(如 Paint 或 Photoshop)合并为 HTML5 画布元素。
我希望能够动态调整画布元素及其像素数据的大小以模拟缩放功能。我的想法是拥有某种包含画布元素的视口。然后我可以调整画布及其在视口内的内容的大小(保持相同的大小)。
我如何最好地实现此功能?
I am working on an application that incorporates a drawing interface (like Paint or Photoshop) as an HTML5 canvas element.
I would like to be able to dynamically resize the canvas element and the pixel data on it to simulate zoom functionality. My thoughts are having some kind of a viewport which contains the canvas element. I could then resize the canvas and its contents inside of the viewport (which stays the same size).
How would I best implement this functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过引入另一个画布将显示与绘图表面分开,您可以非常轻松地做到这一点。使用创建隐藏画布
然后将整个场景绘制到此画布上。然后使用
drawImage
方法将此画布的内容绘制到用户实际可见的另一个画布上(该方法也可能接收画布而不是图像)。如果您想放大绘制场景,可以通过制作源矩形(sy
、sx
、sw
和sw
来完成此操作将隐藏画布绘制到可视画布时,drawImage
上的 >sh 参数会使其变小。这会给你缩放效果。但是,如果您完全重绘画布上的每个框架,您也可以简单地查看 画布对象的
scale
方法。You can do this very easily by seperating the display from the drawing surface by introducing another canvas. Create a hidden canvas using
Then draw your entire scene to this canvas. Then draw the contents of this canvas to another canvas that is actually visible to the user using the
drawImage
method (which may also receive a canvas instead of an image). If you want to draw your scene zoomed in, you can do this by making the source rectangle (thesy
,sx
,sw
andsh
parameters ondrawImage
) on the hidden canvas smaller, when drawing it to the visual canvas. This will give you the zooming effect.However, if you completely redraw each frame on your canvas anyway, you may also simply have a look at the
scale
method of the canvas object.我在画布元素及其内容上成功使用了transform:scale()。
但是,在需要将 canvas 元素与 iframe 一起引入并且转换:缩放发生在 iframe 上的情况下,它适用于 safari,但不适用于移动 safari。下面的相关链接
https://stackoverflow.com/questions/11265483/inconsistcies -when-transform-scale-on-iframe-containing-canvas
I'm having success using transform: scale() on a canvas element and its contents.
However in situations where the canvas element needs to be brought in with an iframe and the transform: scale happens on the iframe it works on safari but not mobile safari. Relevant link below
https://stackoverflow.com/questions/11265483/inconsistencies-when-transform-scale-on-iframe-containing-canvas