<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/underscore.js/1.9.1/underscore.js"></script>
<style>
body {
margin: 100px;
}
</style>
</head>
<body>
<canvas id="canvas">此浏览器不支持绘图</canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 900;
canvas.height = 600;
canvas.style.backgroundColor = "black";
class Ball {
/**构造器*/
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.r = 30;
}
/** 绘制小球方法*/
render() {
ctx.save();
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
}
}
class MoveBall extends Ball{
constructor(x,y,color){
super(x,y,color);
//量的变化
this.dX = _.random(-5,5);
this.dY = _.random(-5,5);
this.dR = _.random(1,2)
}
upDate(){
this.x += this.dX;
this.y += this.dY;
this.r -= this.dR;
if(this.r < 0){
this.r = 0;
}
}
}
//存储小球对象的数组
let ballArr = [];
//存储颜色的数组
let colorArr = ['red','green','blue','yellow','purple','pike','orange'];
//监听鼠标移动事件
canvas.addEventListener("mousemove", function (e) {
ballArr.push(new MoveBall(e.offsetX,e.offsetY,colorArr[_.random(0,colorArr.length-1)]));
});
setInterval(function(){
//清屏
ctx.clearRect(0,0,canvas.width,canvas.height);
//绘制
for(let i = 0;i<ballArr.length;i++){
ballArr[i].render();
ballArr[i].upDate();
}
},50)
</script>
</body>
</html>
canvas绘制多彩小球
猜你喜欢
转载自blog.csdn.net/Byte_Dance/article/details/86543701
今日推荐
周排行