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

查看:26
本文介绍了如何调整 html 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:

未捕获的异常:[异常...WrappedNative原型对象上的非法操作"nsresult:0x8057000c(NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"位置:JS框架:: file:///home/russh/Desktop/test.html ::onclick :: line 1" 数据:无]

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);
};

如你所见,它定义了2个属性widthheight,它们都是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天全站免登陆