前端小蜗牛_
2017-07-20 15:47
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>五角星</title>
</head>
<body>
<canvas id="canvas" style="border:1px solid grey;margin: 50px auto;display: block;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
canvas.width = 1024;
canvas.height = 500;
/* 简单五角星
function drawStar(cxt,r,R,x,y,rot){
cxt.beginPath();
for(var i=0;i<5;i++){
cxt.lineTo(Math.cos((18 + i*72 -rot)/180 * Math.PI) * R + x,
-Math.sin((18 + i*72 -rot)/180 * Math.PI) * R + y);
cxt.lineTo(Math.cos((54 + i*72 -rot)/180 * Math.PI) * r + x,
-Math.sin((54 + i*72 -rot)/180 * Math.PI) * r + y);
}
cxt.closePath();
cxt.stroke();
}
drawStar(context,100,200,300,200,30)*/
//代码优化
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 rot = Math.random() * 360;
drawStar(context,x,y,r,rot)
}
function drawStar(cxt,x,y,r,rot){
cxt.save()
cxt.translate(x,y);
cxt.rotate(rot/180 * Math.PI);
cxt.scale(r,r);
startPath(cxt);
cxt.fillStyle = '#fb3';
cxt.stokeStyle = '#fd5';
// cxt.lineWidth = 3;
// cxt.lineJoin = 'round';
cxt.fill();
cxt.stroke();
cxt.restore();
console.log(r)
}
function startPath(cxt){
cxt.beginPath();
for(var i=0;i<5;i++){
cxt.lineTo(Math.cos((18 + i*72 -rot)/180 * Math.PI) ,
-Math.sin((18 + i*72 -rot)/180 * Math.PI) );
cxt.lineTo(Math.cos((54 + i*72 -rot)/180 * Math.PI) * 0.5,
-Math.sin((54 + i*72 -rot)/180 * Math.PI) * 0.5 );
}
cxt.closePath();
}
</script>
</body>
</html>
好吧,自问自答,也是坑了。scale把边框也给放大了,把填充色给覆盖了...
Canvas绘图详解
72881 学习 · 422 问题
相似问题