Javascript 可以从 Canvas 构造函数创建 HTML5 Canvas 元素吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8330956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:35:48  来源:igfitidea点击:

can the HTML5 Canvas element be created from the Canvas constructor

javascripthtmlcanvas

提问by Overfloater

I would like to be able to make Canvas elements from the constructor so that I could make a function like this.

我希望能够从构造函数制作 Canvas 元素,以便我可以制作这样的函数。

function createCanvasContext(height,width)
{
   var body =  document.getElementsById('body')[0];
   var canvas = new Canvas();
   canvas.height=height;
   canvas.width = width;
   var context = canvas.getContext('2d');
   body.appendChild(canvas);
   return context;
}

I get an error at the line var canvas = new Canvas() saying that 'Canvas is undefined' does HTML5 not allow creating elements from the constructor? or are there parameters that I need to pass to the constructor. Any ideas would be great.

我在 var canvas = new Canvas() 行收到错误,说“Canvas 未定义”HTML5 是否不允许从构造函数创建元素?或者我需要传递给构造函数的参数。任何想法都会很棒。

回答by Simon Sarris

While you can do new Image()just fine, new Canvas()isn't a thing! CanvasIsn't even a thing, though HTMLCanvasElementis. Nonetheless you cannot use its constructor.

虽然你可以做得new Image()很好,但new Canvas()不是一回事!Canvas甚至不是一件事,虽然HTMLCanvasElement是。尽管如此,你不能使用它的构造函数。

document.createElement('canvas');is what you want. You have to use that, just like with divs.

document.createElement('canvas');是你想要的。你必须使用它,就像使用 div 一样。

回答by yapingchen

var mycanvas = document.createElement("canvas");
mycanvas.id = "mycanvas";
document.body.appendChild(mycanvas);