如何调整html canvas元素的大小? [英] How to resize html canvas element?

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

问题描述

我有一个canvas元素静态定义在html的宽度和高度。如果我尝试使用JavaScript来动态调整大小(设置一个新的宽度和高度 - 在画布的属性或通过样式属性),我得到以下错误在Firefox中:

I have a canvas element defined statically in the html with a width and height. If I attempt to use JavaScript to resize it dynamically (setting a new width and height - either on the attributes of the canvas or via the style properties) I get the following error in Firefox:


uncaught exception:[Exception ...对WrappedNative原型对象的非法操作nsresult:0x8057000c(NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)location:JS frame :: file:/// home / russh /Desktop/test.html :: onclick :: line 1data:no]

uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: file:///home/russh/Desktop/test.html :: onclick :: line 1" data: no]

可以调整此元素我必须摧毁它,并在飞行中创建一个新的元素?

Is it possible to resize this element or do I have to destroy it and create a new element on the fly?

推荐答案

您没有发布代码,我怀疑您做错了。可以通过使用数字分配宽度和高度属性来更改大小:

You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:

canvasNode.width  = 200; // in pixels
canvasNode.height = 100; // in pixels

至少它适用于我。确保您不分配字符串(例如,2cm,3in或2.5px),不要混淆样式。

At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.

这是一个公开的知识您可以在 HTML画布规格中阅读所有内容—它是非常小,异常信息。这是整个DOM接口:

Actually this is a publicly available knowledge — you can read all about it in the HTML canvas spec — it is very small and unusually informative. This is the whole DOM interface:

interface HTMLCanvasElement : HTMLElement {
           attribute unsigned long width;
           attribute unsigned long height;

  DOMString toDataURL();
  DOMString toDataURL(in DOMString type, [Variadic] in any args);

  DOMObject getContext(in DOMString contextId);
};

正如你所看到的,它定义了两个属性 width height ,它们都是 unsigned long

As you can see it defines 2 attributes width and height, and both of them are unsigned long.

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

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