源代码:
window.onload = function(){
var canvas = document.getElementById(“canvas”);
var context=canvas.getContext(“2d”);
//绘制和画布一样大小的黑色矩形
context.fillStyle = “black”;
context.fillRect(0,0,canvas.width,canvas.height);
//调用构造五角星函数,并随机产生多个五角星
for(var i = 0;i < 130;i++){
//随机大圆半径
var r = Math.random() * 10 + 10;
var x =Math.random() * canvas.width;
var y =Math.random() * canvas.height;
//随机旋转角0-360
var a =Math.random() * 360;
drawstar(context,x,y,r,r/2.0,a);
}
}
//定义五角星函数,注意在javascript中三角函数要求角度转换为弧度,x,y为五角星的偏移量,rot为图形旋转角度
function drawstar(cxt,x,y,outerR,innnerR,rot){
cxt.beginPath();
for(var i = 0;i < 5;i ++){
cxt.lineTo(Math.cos((18 + i * 72 – rot)/180 *Math.PI)*outerR + x,-Math.sin((18 + i * 72 – rot)/180*Math.PI)*outerR + y);
cxt.lineTo(Math.cos((54 + i * 72 – rot)/180 *Math.PI)*innnerR + x,-Math.sin((54 + i * 72 – rot)/180*Math.PI)*innnerR + y);
}
cxt.closePath();
//状态
cxt.fillStyle = “#fd5”;
cxt.strokeStyle = “#fb5”;
cxt.lineWidth = 3;
cxt.lineJoin = “round”;
//执行
cxt.fill();
cxt.stroke();
}