基于画布canvas实现的小案例,监听画布上的鼠标移动事件,根据其坐标绘制小球,实现小球的半径的减小。颜色的随机。
效果如下:
比较简单,就不多说,直接上代码了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>MovingBall</title>
<style>
body {
margin: 150px;
}
</style>
</head>
<body>
<canvas id="mycanvas"></canvas>
<script>
let canvas = document.getElementById("mycanvas");
let cxt = canvas.getContext("2d");
canvas.width = 1000;
canvas.height = 600;
canvas.style.background = "#000";
class Ball {
/**
*构造器
*/
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.r = 40;
}
/**
*绘制小球
*/
render() {
cxt.save() //保存
cxt.beginPath();
cxt.arc(this.x, this.y, this.r, 0, Math.PI * 2);
cxt.fillStyle = this.color;
cxt.fill()
cxt.restore();
}
}
class MoveBall extends Ball {
constructor(x, y, color) {
super(x, y, color);
//位置和半径的变化
this.dX = Math.random(-5, 5);
this.dY = Math.random(-5, 5);
this.dR = Math.random(1, 4);
}
UpDate() {
this.x += this.dX;
this.y += this.dY;
this.r -= this.dR;
if (this.r < 0) {
this.r = 0;
}
}
}
let Balls = [];
const colors = ['red', 'purple', 'green', 'orange', 'white', 'pick', 'blue', 'skyblue', 'yellow'];
canvas.addEventListener('mousemove', (e) => {
Balls.push(new MoveBall(e.offsetX, e.offsetY, colors[Math.floor(Math.random() * colors.length)]))
})
setInterval(() => {
cxt.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < Balls.length; i++) {
Balls[i].render();
Balls[i].UpDate();
}
}, 50);
</script>
</body>
</html>