当前位置: 首页 > Web前端 > HTML

【面向对象案例】实现小球在画布内的随机运动

时间:2023-04-02 22:08:54 HTML

//css部分,为画布设置边框//html添加画布准备工作首先确定起始xy坐标、R半径、颜色、速度speedXY需要的属性球。//创建球构造函数ball(){this.r=this.rand(20);这个.x=这个.r;这个.y=这个.r;this.speedX=this.rand(10);这.speedY=this.rand(10);这个.width=0;这个.height=0;这个.canvas={};this.color='rgb('+this.rand(255)+','+this.rand(255)+','+this.rand(255)+')';这个。初始化();}//2。添加methodball.prototype={init:function(){vargame到原型链=document.getElementById('game');this.canvas=game.getContext('2d');this.width=游戏.width;this.height=游戏.height;},rand:function(num){returnMath.floor(Math.random()*num+1);},play:function(){this.x+=this.speedX;this.y+=this.speedY;如果(this.x>this.width-this.r){this.speedX=-this.speedX;}if(this.xthis.width-this.r){this.speedY=-this.speedY;}if(this.y