鼠标跟随炫酷效果

canvas画布上监听鼠标移动事件并画图,随机小球颜色,随机小球运动方向,当小球透明度到一定程度,清除小球





    
    
    
    鼠标跟随
    



    
    


js代码: 

var canvas = document.getElementById('demo')
var ctx = canvas.getContext('2d')
var starlist = []  



function size() {
    canvas.height = window.innerHeight
    canvas.width = window.innerWidth
}
size()
window.onresize = size

//监听鼠标移动事件,画小球
canvas.addEventListener('mousemove', function (e) {
    //创建小球信息类的对象,加到一个数组中,每一个对象代表一个小球
    starlist.push(new Star(e.offsetX, e.offsetY, ctx))
})


//创建一个包含小球信息的类
class Star {
    constructor(x, y, ctx) {
        this.x = x
        this.y = y
        this.ctx = ctx
        this.vx = (Math.random() - 0.5) * 3
        this.vy = (Math.random() - 0.5) * 3
        this.a = 1
        this.color = `rgb(${this.random(0,255)},${this.random(0,255)},${this.random(0,255)})`
        this.draw()
    }

    random(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min)
    }
    
    //小球在画布上的画法
    draw() {
        this.ctx.beginPath()
        this.ctx.fillStyle = this.color
        this.ctx.globalCompositeOperation = 'lighter'
        this.ctx.globalAlpha = this.a
        this.ctx.arc(this.x, this.y, 30, 0, Math.PI * 2)
        this.ctx.fill()
        this.update()
    }
    
    //下一帧小球改变的位置和透明度
    update() {
        this.x += this.vx
        this.y += this.vy
        this.a *= 0.98
    }
}

function render() {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    starlist.forEach(function (item, index) {
        item.draw()
        if (item.a < 0.05) {
            starlist.splice(index, 1)
        }
    })
    requestAnimationFrame(render)
}

render()

 

 

 

 

你可能感兴趣的:(鼠标跟随炫酷效果)