<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>鼠標demo</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
//設置畫布
const canvas=document.getElementById("canvas");
const ctx=canvas.getContext('2d');
canvas.width=1900;
canvas.height=900;
canvas.style.backgroundColor = "#000";
let ballArr = [];
let colorArr = ['red', "blue", 'green'];
let mouseInCanvas = false;
let offsetX;//通過事件獲取鼠標X
let offsetY;//通過事件獲取鼠標Y
let r = 150;//球的半徑
//小球類
class Ball{
constructor(x,y,color){
this.x=x;
this.y=y;
this.color=color;
this.r=r;
}
//繪製小球
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);
}
Update(){
this.x += this.dX;
this.y += this.dY;
this.r -= this.dR;
if (this.r < 0) {
this.r = 0;
}
}
}
//鼠標移動
canvas.addEventListener('mousemove',
function(e) {
mouseInCanvas = true;
offsetX = e.offsetX;
offsetY = e.offsetY;
});
//鼠標出畫布
canvas.addEventListener('mouseout',
function(e) {
mouseInCanvas = false;
});
//鼠標進畫布
canvas.addEventListener('mouseover',
function(e) {
mouseInCanvas = true;
});
setInterval(function () {
if (mouseInCanvas) {
//圓圈移動
ballArr.push(new MoveBall(offsetX, offsetY, colorArr[1]));
}
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>