can the HTML5 Canvas element be created from the Canvas constructor

JavascriptHtmlCanvas

Javascript Problem Overview


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

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.

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOverfloaterView Question on Stackoverflow
Solution 1 - JavascriptSimon SarrisView Answer on Stackoverflow
Solution 2 - JavascriptyapingchenView Answer on Stackoverflow