我正在尝试在我的网站上执行javascript,但我得到了:
未捕获的TypeError:无法读取null的“getContext”属性
我不知道我做错了什么。它只在一个网站上完美执行..
这是脚本代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var dots = [];
var r = Math.floor(Math.random() * 255) + 125;
var g = Math.floor(Math.random() * 255) + 125;
var b = Math.floor(Math.random() * 255) + 125;
var radius = Math.floor(Math.random() * 2) + 1;
function Dot(xCoordinate, yCoordinate, radiusValue, rValue, gValue, bValue, aValue) {
this.x = xCoordinate;
this.y = yCoordinate;
this.radius = radiusValue;
this.r = rValue;
this.g = gValue;
this.b = bValue;
this.a = aValue;
}
function dotFilter(element) {
return element.y >= 0 && element.a >= 0;
}
function drawDots() {
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
if (dots.length === 0) {
return;
}
dots = dots.filter(dotFilter);
for (i = 0; i < dots.length; i = i + 1) {
dots[i].y = dots[i].y - 12;
dots[i].a = dots[i].a - .03;
ctx.save();
ctx.beginPath();
ctx.arc(dots[i].x, dots[i].y, dots[i].radius, 0, 4 * Math.PI, true);
ctx.fillStyle = "rgba(" + dots[i].r + "," + dots[i].g + "," + dots[i].b + "," + dots[i].a + ")";
ctx.fill();
ctx.restore();
}
}
canvas.onmousemove = function(e) {
var mouseX, mouseY;
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
} else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
r = Math.floor(Math.random() * 255) + 50;
g = Math.floor(Math.random() * 255) + 50;
b = Math.floor(Math.random() * 255) + 50;
radius = Math.floor(Math.random() * 2) + 1;
dots.push(new Dot(mouseX - 12, mouseY - 12, radius, r, g, b, 1));
};
function clearScreen() {
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
}
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
window.setInterval(drawDots, 70);