樱花飞落ll
2016-08-30 09:14
在谷歌浏览器中显示效果如下图,不知道是什么问题,感觉代码都跟老师的差不多
在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();
}
问题出在绘制五角星路径,Chrome下ctx.clip();存在问题,绘制多边形如果角度太小ctx.clip();的剪切就会超出路径范围,如果你换成三角形或是圆形四方形 就不存在这些问题。怎么解决我也不知道。
Canvas绘图详解
72881 学习 · 422 问题
相似问题