怎么在JavaScript中使用canvas实现一个跟随鼠标事件

发布时间:2021-04-16 17:54:56 作者:Leah
来源:亿速云 阅读:137

这期内容当中小编将会给大家带来有关怎么在JavaScript中使用canvas实现一个跟随鼠标事件,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

<!DOCTYPE html>
<html>

<head>
 <meta charset="UTF-8">
 <title></title>
 <style>
 body {
 margin: 0;
 overflow: hidden;
 }

 #canvas {
 background: #000;
 }
 </style>
</head>

<body>
 <canvas id="canvas"></canvas>
 <script>
 var canvas = document.getElementById('canvas');
 var context = canvas.getContext('2d');
 var circleList = [];

 canvas.width = window.innerWidth;
 canvas.height = window.innerHeight;

 canvas.addEventListener('mousemove', function (e) {
 // 将对象push到数组中,画出来的彩色小点可以看作每一个对象中记录着信息 然后存在数组中
 circleList.push(new Circle(e.clientX, e.clientY));
 })

 //取x到y之间随机数:Math.round(Math.random()*(y-x)+x) 包括y
 function random(min, max) {
 return Math.round(Math.random() * (max - min) + min);
 }

 function Circle(x, y) {
 this.x = x;
 this.y = y;

 this.vx = (Math.random() - 0.5) * 3; //随机出来一个正数,或者负数。乘3是为了让速度变得大一点
 this.vy = (Math.random() - 0.5) * 3;

 this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')';

 this.a = 1; // 初始透明度

 this.draw();
 }
 Circle.prototype = {
 draw() {
 context.beginPath();
 context.fillStyle = this.color;
 context.globalCompositeOperation = 'lighter';
 context.globalAlpha = this.a; //全局透明度
 context.arc(this.x, this.y, 30, 0, Math.PI * 2, false);
 context.fill();
 this.update();
 },
 update() {
 // 根据速度更新每一个小圆的位置
 this.x += this.vx;
 this.y += this.vy;
 this.a *= 0.98;
 }
 }

 function render() {
 //把原来的内容区域清除掉
 context.clearRect(0, 0, canvas.width, canvas.height);
 circleList.forEach(function (ele, i) {
 ele.draw();

 if (ele.a < 0.05) {
  circleList.splice(i, 1);
 }
 });

 requestAnimationFrame(render); //动画,会根据浏览器的刷新频率更新动画
 }
 render();
 </script>
</body>

</html>

上述就是小编为大家分享的怎么在JavaScript中使用canvas实现一个跟随鼠标事件了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么在JavaScript中使用canvas实现一个扫雷小游戏
  2. 怎么在JavaScript中使用canvas实现一个前端截图工具

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

canvas javascript

上一篇:怎么在Python中实现一个守护进程

下一篇:使用jQuery怎么实现一个聊天框

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》