Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 277
ljos Avatar asked Feb 14 '26 05:02

ljos


1 Answers

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.

like image 159
Simon Sarris Avatar answered Feb 15 '26 17:02

Simon Sarris