ljos
ljos

Reputation: 315

Cannot draw on canvas

I have been trying to insert a canvas on top of some pages, but for some pages it doesn't work. It seems to be me that there is something clearing all canvases on the page, but I couldn't find any calls to .clearRect anywhere in the code on the page.

canvas = document.createElement('canvas');
canvas.width = document.width;
canvas.height = document.height;

canvas.style['z-index'] = 999;
canvas.style.position = 'absolute';
canvas.style.top = 0;
canvas.style.left = 0;

document.body.appendChild(canvas);

var ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 1000, 1000);

A page with the problem is: http://www.nrk.no/sognogfjordane/helse-forde-har-ikkje-full-oversikt-1.11166801

If you run the same code on this page it should work. Expected result is a huge black square on the page.

I don't understand how a script can block the use of an inserted canvas on the page.

I am using Chrome.

* EDIT *

The problem is not that I use the deprecated document.width/heightcalls, but that I wasn't aware that canvas has a maximum size: Maximum size of a <canvas> element

Upvotes: 3

Views: 3019

Answers (3)

ljos
ljos

Reputation: 315

I first thought Simon Sarris was correct, but in the end that didn't do what I wanted. What I want is a that covers the entire page.

I discovered through Maximum size of a <canvas> element that I was exceeding the limits of canvas.

Upvotes: 0

Deepak Biswal
Deepak Biswal

Reputation: 4320

Please look into the demo.

canvas = document.createElement('canvas');
canvas.width = document.width;
canvas.height = document.height;

canvas.style['z-index'] = 999;
canvas.style.position = 'absolute';
canvas.style.top = 0;
canvas.style.left = 0;

document.body.appendChild(canvas);

var ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 1000, 1000);

I think this is what you needed. If you need something else then please exaplin or put your code in jsfiddle. Here in this demo it is creating canvas element.

Upvotes: 0

Simon Sarris
Simon Sarris

Reputation: 63812

Because document.width and document.height are undefined, so your canvas width and height are 0 and 0.

Instead try something like:

canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

canvas.style['z-index'] = 999;
canvas.style.position = 'absolute';
canvas.style.top = 0;
canvas.style.left = 0;

document.body.appendChild(canvas);

var ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 1000, 1000);

And you'll see it just fine.

See notes on the MDN. Specifically:

Starting in Gecko 6.0, document.width is no longer supported. Instead, use document.body.clientWidth.

Upvotes: 4

Related Questions