无法在画布上绘制

3

我一直在尝试在一些页面上插入一个 canvas,但是对于某些页面它不起作用。我觉得可能是有些东西在清除页面上的所有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调用,而是我不知道画布有最大尺寸限制:Canvas元素的最大尺寸


1
你是如何在哪里插入这段代码的?我将它放到控制台中,对我来说(在Chrome中)它运行得很好。 - dan-lee
3个回答

4

由于document.widthdocument.height未定义,因此您的画布宽度和高度为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


谢谢。这个可以运行,但是我不明白为什么我的代码在一些页面上可以运行,在另一些页面上却不能。 - ljos
仔细想想,这并不像我想要的那样。我希望画布覆盖整个页面,但在某些页面上超出最大画布大小。请参见https://dev59.com/0m025IYBdhLWcg3wUEOP - ljos

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

我认为这就是你需要的。如果你需要其他东西,请解释一下或将你的代码放在jsfiddle中。在这个演示中,它正在创建画布元素。


如果您想要特定的宽度和高度,则必须指定 document.widthdocument.height,否则它将填充窗口。 - Deepak Biswal

0

起初我认为Simon Sarris是正确的,但最终那并不是我想要的。我想要的是一个覆盖整个页面的<canvas>。

通过 <canvas>元素的最大尺寸我发现自己超出了画布的限制。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接