调整HTML5画布元素的大小 [英] Resize HTML5 canvas element

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

问题描述

如何实现,以便HTML5 canvas元素可以调整大小?

How can I achieve, so that the HTML5 canvas element ist resizeable?

我想实现这个元素,以便您可以缩放任何大小。缩放的事件应该是鼠标捕捉边缘,并且用户调整元素的大小。

I would like to implement this element so that you can scale it in any size. The event of the scaling should be the mouse which snaps the edge and the user resizes the element.

我已经阅读了如何在一个对象上实现这个canvas元素。但在我的case我需要这个在canvas元素本身(< canvas> )。

I've already read about how you can achieve this on a object in the canvas element. But in my case I need this on the canvas element itself (<canvas>).

推荐答案

设置画布的宽度或高度属性具有清除画布的效果。甚至 canvas.width = canvas.width ;会使你失去画布中的一切。有时这是可取的,但在你的情况下,它可能不是。

Setting a canvas's width or height properties has the effect of clearing the canvas. Even canvas.width = canvas.width; will cause you to lose everything in the canvas. Sometimes this is desirable, but in your case it probably isn't.

您可能需要做的是这样的

What you will probably need to do is something like this

 var myCanvas = document.getElementById('myCanvas');
 var tempCanvas = document.createElement('canvas');
 tempCanvas.width = myCanvas.width;
 tempCanvas.height = myCanvas.height;

 // save your canvas into temp canvas
 tempCanvas.getContext('2d').drawImage(myCanvas, 0, 0);

 // resize my canvas as needed, probably in response to mouse events
 myCanvas.width = newWidth;
 myCanvas.height = newHeight;

 // draw temp canvas back into myCanvas, scaled as needed
 myCanvas.getContext('2d').drawImage(tempCanvas, 0, 0, tempCanvas.width, tempCanvas.height, 0, 0, myCanvas.width, myCanvas.height);

在大多数浏览器中,缩放将使用双三次缩放算​​法,导致其变得模糊。在某些情况下,你可以设置一个CSS属性在画布上导致最近邻,如果你想,但浏览器支持这是非常多斑点现在。您可以手动执行最近邻的缩放,如此问题所示:如何没有抗锯齿的拉伸图片

In most browsers, the scaling will be done with a bicubic scaling algorithm, causing it to get blurry. In some cases you can set a CSS property to cause nearest neighbor on the canvas if you want, but browser support for this is very spotty right now. You can instead manually do a nearest neighbor scale , as this question shows: How to stretch images with no antialiasing

另一种方法是使用CSS。在Chrome / Safari / IE中,您只需执行:

Another approach is to scale the canvas using CSS. In Chrome/Safari/IE you can just do:

<canvas style="zoom:200%" />

在Firefox中,您可以使用比例变换实现相同的效果:

In Firefox, you can use a scale transform to achieve the same effect:

<canvas style="-moz-transform:scale(2)" />

在许多方面,这种方法更容易,但它自带的小问题和浏览器特定的怪癖。

In many ways this approach is easier, but it comes with its own little gotchas and browser specific quirks.

这篇关于调整HTML5画布元素的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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