五角星探照灯 没有完全盖住下面的文字
在谷歌浏览器中显示效果如下图,不知道是什么问题,感觉代码都跟老师的差不多
在360浏览器中正常显示,如下图所示:
代码如下
var searchLight = {
x: 400,
y: 400,
radius: 150,
vx: Math.random() * 5 + 10,
vy: Math.random() * 5 + 10
}
var rot = 0;
var isIncreased = true;
window.onload = function() {
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 800;
var ctx = canvas.getContext("2d");
setInterval(function() {
draw(ctx);
update(canvas.width, canvas.height);
//update2();
}, 40)
}
function draw(ctx) {
var canvas = ctx.canvas;
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.save();
ctx.beginPath();
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(searchLight.x, searchLight.y);
ctx.rotate(rot / 180 * Math.PI)
ctx.scale(searchLight.radius, searchLight.radius);
startPath(ctx)
ctx.fillStyle = "#fff";
//ctx.arc(searchLight.x, searchLight.y, searchLight.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
ctx.clip();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "bold 150px Arial";
ctx.fillStyle = "#058";
ctx.fillText("CANVAS", canvas.width / 2, canvas.height / 4);
ctx.fillText("CANVAS", canvas.width / 2, canvas.height / 2);
ctx.fillText("CANVAS", canvas.width / 2, canvas.height * 3 / 4);
ctx.restore();
}
function update(width, height) {
rot += 1;
searchLight.x += searchLight.vx;
searchLight.y += searchLight.vy;
console.log(searchLight.x, searchLight.y);
//碰撞检测
//右边
if (searchLight.x + searchLight.radius >= width) {
searchLight.x = width - searchLight.radius;
searchLight.vx = -searchLight.vx;
}
//左边
if (searchLight.x - searchLight.radius <= 0) {
searchLight.x = searchLight.radius;
searchLight.vx = -searchLight.vx;
}
//上边
if (searchLight.y - searchLight.radius <= 0) {
searchLight.y = searchLight.radius;
searchLight.vy = -searchLight.vy;
}
//下边
if (searchLight.y + searchLight.radius >= height) {
searchLight.y = height - searchLight.radius;
searchLight.vy = -searchLight.vy;
}
}
//画五角星
function startPath(ctx) {
ctx.beginPath();
for (var i = 0; i < 5; i++) {
ctx.lineTo(Math.cos((18 + i * 72) / 180 * Math.PI), -Math.sin((18 + i * 72) / 180 * Math.PI));
ctx.lineTo(Math.cos((54 + i * 72) / 180 * Math.PI) * 0.5, -Math.sin((54 + i * 72) / 180 * Math.PI) * 0.5);
}
ctx.closePath();
}