这是一段鼠标追随特效的JS代码,试了很多遍都是这两个地方错,还望各位能给点建议

该代码示例展示了如何使用JavaScript生成随机位置和速度的小球,并在HTML5画布上绘制。小球在画布上移动并随时间逐渐变透明。当鼠标在画布上移动时,会根据鼠标位置创建新的小球。代码利用requestAnimationFrame实现平滑动画效果。
摘要由CSDN通过智能技术生成

代码如下:

var BallList = [] // 存储球的对象

/**
 * @param {Object} min 2
 * @param {Object} max 10
 * 产生一个 min ~ max 的随机数
 */
function random(min, max) {
    // Math.random()方法返回大于等于 0 小于 1 的一个随机数
   ********* // 此处代码为第一处
}

// 构造函数 创建球形对象
function Ball(x, y) {
    this.x = x
    this.y = y
    this.r = 30
    this.vx = random(-5, 5)
    this.vy = random(-5, 5)
    this.colorList = ['red', 'pink', 'black', 'green', 'yellow']
    this.color = this.colorList[Math.floor(random(0, 6))]
    this.a = 1 // 透明度
    this.va = 0.95 // 透明度变化
}

// 绑定原型  减少性能消耗
Ball.prototype = {
    // 更新
    update: function() {
        this.x += this.vx
        this.y += this.vy
        this.a *= this.va
    },
    // 画圆
    draw: function(ctx) {
        // 重置
        ctx.beginPath()
        ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI)
        ctx.fillStyle = this.color
        ctx.globalAlpha = this.a
        ctx.globalCompositeOperation = "lighter"
        ctx.fill()
        // 更新
        this.update()
    }
}

// var ball = new Ball(100, 100)
// console.log(ball)

// 设置定时器
window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function(callback) {
            // 1000/60,这是因为大多数屏幕渲染的时间间隔是每秒60帧
            window.setInterval(callback, 1000 / 60);
        };
})();

// 1.初始化画布
var canvas = document.getElementById("canvas")
// console.log(canvas)
// 2.画笔
var ctx = canvas.getContext("2d")
// 初始化画布的宽 与 高
const initwh = () => {
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
}

// 窗口发生改变 则重新调整画布的宽和高
window.onresize = initwh

// 添加 监听鼠标移动 事件 -> 产生 新球
canvas.addEventListener("mousemove", (e) => {
    // 产生球  =》 根据鼠标的位置
    
    ***********// 此处代码为第二处
})

// 创建 新球
function create(x, y) {
    BallList.push(new Ball(x, y))
}

// 程序入口
function main() {
    ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
    BallList.forEach((item) => {
        item.draw(ctx)
    })

    // 不需要时间参数,它是根据屏幕的刷新率
    requestAnimFrame(main)
}

initwh() // 调整窗体大小
main() // 调用main方法 启动程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值