使用canvans生成50个圆随机排布,使用定时器自动生成,如下图所示效果:
实现代码如下:
<body>
<canvas width="1000px" height="1000px" id="can1" style="border: 2px solid red;"></canvas>
</body>
<script>
window.onload = function() {
var myCan1 = document.getElementById("can1");
var ctx = myCan1.getContext("2d");
var t = 0;
var id = setInterval(frame, 500);
function frame() {
if (t > 50) {
clearInterval(id)
} else {
t++;
var rx = Math.floor(Math.random() * 1000);
var ry = Math.floor(Math.random() * 1000);
var r = Math.floor(Math.random() * 40);
var r1 = Math.floor(Math.random() * 255)
var r2 = Math.floor(Math.random() * 255)
var r3 = Math.floor(Math.random() * 255)
ctx.beginPath(); //开始绘制
ctx.arc(rx, ry, r, 0, 2 * Math.PI); //arc 的意思是“弧”
ctx.fillStyle = `rgb(${r1},${r2},${r3})`
ctx.fill(); //开始填充
ctx.closePath();
}
}
ctx.stroke();
}
</script>