<!DOCTYPE html>
<html>
<head>
<meta content="charset=utf-8"/>
<title>star sky</title>
</head>
<body>
<canvas id="canvas" style="border:1px solid #aaa;display:block;margin:50px auto"></canvas>
</body>
<script>
window.onload = function ()
{
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 800;
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < 200; i++)
{
var r = Math.random() * 10 + 10;
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
var a = Math.random() * 360;
drawStar(context, r, x, y, a);
}
}
function drawStar(cxt, R, x, y,rot)
{
cxt.save();
starPath(cxt);
cxt.translate(x, y);
cxt.rotate(rot / 180 * Math.PI);
cxt.fillStyle = '#fb3';
cxt.strokeStyle = '#fb5';
cxt.lineWidth = 3;
cxt.lineJoin = 'round';
cxt.fill();
cxt.stroke();
cxt.restore();
}
function starPath(cxt)
{
cxt.beginPath();
for (var i = 0; i < 5; i++) {
cxt.lineTo(Math.cos((18 + i * 72) / 180 * Math.PI)*20,
-Math.sin((18 + i * 72) / 180 * Math.PI)*20);
cxt.lineTo(Math.cos((54 + i * 72) / 180 * Math.PI) * 0.5*20,
-Math.sin((54 + i * 72) / 180 * Math.PI) * 0.5*20);
}
cxt.closePath();
}
</script>
</html>
这是我的代码,拜托大神指点一下,之前没有图形变化的时候都可以漫天星星,后来就只能像上传的图片里面那样了,感觉translate和rotate都没有起作用,而且也没有绘制多个,但是颜色等样式又起作用了
绘制图形的点一直在(0,0), 先translate将绘制点移到(x,y),然后开始drawstar才会改变位置
先translate再drawstar