html 怎样将圆点移动,html5_canvas圆点跟随鼠标光标移动

鼠标demo

//设置画布

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[i].render();

ballArr[i].Update();

}

},50);

d7ef40e390bda4b435c1f69b71ba5a90.png

本文来源于网络:查看 >https://blog.csdn.net/agoling/article/details/83142272

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值