For bouncing balls animation at first we need to create a Ball class as shown below :
function Ball(x, y, dx, dy, radius, color) {
if(x === undefined) { x = 50 }
if(y === undefined) { y = 50 }
if(dx === undefined) { dx = 2 }
if(dy === undefined) { dy = 3 }
if(radius === undefined) { radius = 10 }
if(color === undefined) { color = 'green' }
this.radius = radius; this.color = color;
this.x = x; this.y = y;
this.dx = dx; this.dy = dy;
this.draw = function() {
context.save();
context.beginPath();
context.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
context.closePath();
this.y += this.dy; this.x += this.dx;
if(this.y >= canvas.height - this.radius)
{
this.y = canvas.height - this.radius; this.dy = -this.dy;
}
else if(this.y < 0 + this.radius)
{
this.y = 0 + this.radius; this.dy = -this.dy;
}
if(this.x >= canvas.width - this.radius)
{
this.x = canvas.width - this.radius; this.dx = -this.dx;
}
else if(this.x < 0 + this.radius)
{
this.x = 0 + this.radius; this.dx = -this.dx;
}
context.fillStyle = this.color;
context.fill();
context.restore();
}
}
In the above code we have written a draw function which will create the ball according to the radius and color provided. Note we are saving the context at the first line and then restoring it at last line of the draw function, because we do not want our context to get updated with the color supplied. Context saved will be stacked, the last one that has been saved will be restored by the next call to restore(). So it is very important to have one restore with every save.
Now we have to create a new instance of the ball class to start the animation as shown below :
ball = new Ball(x, y, dx, dy, radius, color);
Full Source Code
Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.
分页:12
转载请注明
本文标题:Bouncing Balls Animation using HTML5 Canvas Element
本站链接:
分享请点击:
1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
注册 登录