不能在画布上画画

时间:2013-08-05 16:41:22

标签: javascript html5 canvas html5-canvas

我一直在尝试在某些页面上插入画布,但对于某些页面,它不起作用。似乎是我在页面上清除了所有画布,但我在页面代码中的任何地方都找不到.clearRect的调用。

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);

有问题的页面是:http://www.nrk.no/sognogfjordane/helse-forde-har-ikkje-full-oversikt-1.11166801

如果您在此页面上运行相同的代码,它应该可以工作。预期的结果是页面上有一个巨大的黑色方块。

我不明白脚本如何阻止在页面上使用插入的画布。

我正在使用Chrome。

*编辑*

问题不是我使用已弃用的document.width/height调用,而是我不知道画布的最大大小为:Maximum size of a <canvas> element

3 个答案:

答案 0 :(得分:3)

由于document.widthdocument.height未定义,因此您的画布宽度和高度为0和0。

而是尝试类似:

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);

你会看到它很好。

请参阅MDN.上的说明具体:

  

从Gecko 6.0开始,不再支持document.width。相反,请使用document.body.clientWidth

答案 1 :(得分:0)

请查看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);

我认为这就是你所需要的。如果你需要别的东西,那么请exaplin或把你的代码放在jsfiddle中。在这个演示中,它是创建canvas元素。

答案 2 :(得分:0)

我首先认为西蒙·萨里斯是正确的,但最终却没有做到我想要的。我想要的是涵盖整个页面的内容。

我通过Maximum size of a <canvas> element发现我超出了画布的限制。