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

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

问题描述

如何实现这个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元素本身(< 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 canvas元素的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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