代码如下:
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方法 启动程序