// 获取class名为picture的canvas元素
var can = document.querySelector('.picture');
// 让它撑满整个屏幕
can.width = window.innerWidth;
can.height = window.innerHeight;
// 获取2d上下文
ctx = can.getContext('2d');
// 封装一个类
; (function (win) {
function Circle() {
if (!(this instanceof Circle)) {
return new Circle();
}
this.x = ran(win.innerWidth);//圆心x轴坐标
this.y = ran(win.innerHeight);//圆心y轴坐标
this.r = ran(20);//半径
this.vx = ran(10);//速度
this.vy = ran(10);//速度
this.color = Mock.random.color();//mock.js中的随机颜色api
}
Circle.prototype = {
constructor: Circle,
//画画函数
draw: function (ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 360, true);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
},
// 小球的边界判定函数(回弹)
move: function (ctx) {
var canvasWidth = ctx.canvas.width;
var canvasHeight = ctx.canvas.height;
//判断4个边
if (this.y > (canvasWidth - this.r) || this.y < this.r) {
this.vy = -this.vy;
}
if (this.x > (canvasHeight - this.r) || this.x < this.r) {
this.vx = -this.vx;
}
//偏移量
this.x += this.vx;
this.y += this.vy;
},
// 随机数函数
ran: function (Num) {
return Math.floor(Math.random() * Num);
}
}
//暴露接口
win.Circle = Circle;
}(window));
//调用20次(20和小球同时运动)
var arr = [];
for (var i = 0; i < 20; i++) {
arr.push(Circle())
}
function draw() {
// 清楚之前的画布
ctx.clearRext(0, 0, window.innerWidth, window.innerHeight);
for (var i = 0; i < arr.length; i++) {
var circle = arr[i];
circle.move(ctx);//调用Circle类中的move方法
circle.draw(ctx);//调用Circlr类中的draw方法
}
requestAnimationFrame(draw)//动画函数 递归调用draw函数
}
draw();//首次调用
canvas实现多个弹跳小球 js部分
最新推荐文章于 2022-02-16 10:50:24 发布