TheShadeM
TheShadeM

Reputation: 45

Why is nothing appearing on my canvas?

I am such a noob and I have no idea why nothing is appearing on my canvas. Can someone help me out? I wanted to have a black box on my canvas, that was the intention anyway.

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1040;
canvas.height = 400;
canvas.style.display='block';
canvas.style.marginLeft="auto";
canvas.style.marginRight="auto";

var mainFunction= function(){
ctx.fillStyle = "rgb(0, 0, 0)"; 
ctx.beginPath(); 
ctx.rect(0, 0, canvas.width, canvas.height); 
ctx.closePath(); 
ctx.fill();
requestAnimationFrame(mainFunction);
};

mainFunction();

Upvotes: 0

Views: 106

Answers (2)

Michael Bruce
Michael Bruce

Reputation: 11347

Basically, you do not have an attached canvas to the DOM.

Create a html file with <canvas id="root"></canvas>;

var canvas = document.getElementById("root");

Upvotes: 0

ephemient
ephemient

Reputation: 204758

You have created a <canvas> element but have not attached it anywhere in the DOM. Perhaps you want something like

document.body.appendChild(canvas);

or another suitable container.

Upvotes: 3

Related Questions