1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > html画布实现小球沿直线下落 [面向对象的案例]在canvas画布内实现小球的随机移动...

html画布实现小球沿直线下落 [面向对象的案例]在canvas画布内实现小球的随机移动...

时间:2019-04-27 22:49:43

相关推荐

html画布实现小球沿直线下落 [面向对象的案例]在canvas画布内实现小球的随机移动...

//css部分,给画布设置边框

canvas {

border:1px solid orange;

}

//html 添加画布

准备工作

先确定所需要的属性

小球的起始xy坐标、R半径、颜色、速度speedXY。

//创建球构造函数

function ball() {

this.r = this.rand(20);

this.x = this.r;

this.y = this.r;

this.speedX = this.rand(10);

this.speedY = this.rand(10);

this.width = 0;

this.height = 0;

this.canvas = {};

this.color = 'rgb('+this.rand(255)+','+this.rand(255)+','+this.rand(255)+')';

this.init();

}

//2.向原型链添加方法

ball.prototype = {

init:function () {

var game = document.getElementById('game');

this.canvas = game.getContext('2d');

this.width=game.width;

this.height=game.height;

},

rand:function (num) {

return Math.floor(Math.random() * num+1);

},

play:function () {

this.x += this.speedX;

this.y += this.speedY;

if (this.x>this.width-this.r) {

this.speedX = -this.speedX;

}

if (this.x

this.speedX = Math.abs(this.speedX);

}

if (this.y>this.width-this.r) {

this.speedY = -this.speedY;

}

if (this.y

this.speedY = Math.abs(this.speedY);

}

this.canvas.beginPath();

this.canvas.fillStyle = this.color;

this.canvas.arc(this.x, this.y, this.r, 0, 2 * Math.PI);

this.canvas.fill();

}

};

//3.创建100个小球

var arr = [];

for (var i=0;i<100;i++) {

arr[i] = new ball();

}

//4.使用定时器,每个30ms刷新屏幕

setInterval(function () {

arr[0].canvas.clearRect(0,0,500,500);

for (var i=0;i

arr[i].play();

}

},30)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。