欢迎光临
我们一直在努力

基于canvas的超酷跟随鼠标粒子动画

这是一款基于canvas的超酷跟随鼠标粒子动画特效。该粒子跟随动画特效通过js代码,在canvas上随机生成粒子效果,并使粒子跟随鼠标移动而移动。

代码演示

https://codepen.io/sedran/pen/oaOyvK

使用教程

引入方式

在页面中引入stopExecutionOnTimeout.js文件。


HTML部分

在页面中创建一个canvas。


CSS代码

 
为canvas添加下面的CSS样式。
 


html{
  margin: 0;
  padding: 0;
  border: 0;
  font-family:  sans-serif;
}
 
canvas{
  margin: 0;
  padding: 0;
  display: block; 
  touch-action: none; 
}

JavaScript

 
在页面DOM元素加载完毕之后,通过下面方法来制作粒子跟随鼠标效果。
 


var canvas = document.querySelector('canvas');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
c = canvas.getContext('2d');
 
window.addEventListener('resize', function () {
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;
 
    initCanvas();
});
 
var mouse = {
    x: undefined,
    y: undefined };
 
window.addEventListener('mousemove',
function (event) {
    mouse.x = event.x;
    mouse.y = event.y;
    drawCircles();
});
 
window.addEventListener("touchmove",
function (event) {
    let touch = event.touches[0];
    mouse.x = touch.clientX;
    mouse.y = touch.clientY;
    drawCircles();
});
 
 
function Circle(x, y, radius, vx, vy, rgb, opacity, birth, life) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.minRadius = radius;
    this.vx = vx;
    this.vy = vy;
    this.birth = birth;
    this.life = life;
    this.opacity = opacity;
 
    this.draw = function () {
        c.beginPath();
        c.arc(this.x, this.y, this.radius, Math.PI * 2, false);
        c.fillStyle = 'rgba(' + rgb + ',' + this.opacity + ')';
        c.fill();
    };
 
    this.update = function () {
        if (this.x + this.radius > innerWidth || this.x - this.radius  innerHeight || this.y - this.radius  this.birth + this.life) {
            for (let i = 0; i 

文章来源于互联网:基于canvas的超酷跟随鼠标粒子动画

赞(0)
未经允许不得转载:莱卡云 » 基于canvas的超酷跟随鼠标粒子动画