canvas教程

Bouncing Balls Animation using HTML5 Canvas Element

字号+ 作者:H5之家 来源:H5之家 2015-11-03 10:27 我要评论( )

Bouncing Balls Animation using HTML5 Canvas Element,ForbouncingballsanimationatfirstweneedtocreateaBallclassasshownbelow:functionBall(x,y,dx,dy,radius

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;


Bouncing Balls Animation using HTML5 Canvas Element


}

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.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。

登录后可拥有收藏文章、关注作者等权限...

   注册     登录

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • html5canvas核心技术图形、动画与游戏开发源码

    html5canvas核心技术图形、动画与游戏开发源码

    2017-05-02 17:42

  • 打印html5中Canvas的方法

    打印html5中Canvas的方法

    2017-05-01 15:03

  • HTML样式CSS

    HTML样式CSS

    2017-05-01 10:03

  • HTML5+Canvas调用手机拍照功能实现图片上传(下)

    HTML5+Canvas调用手机拍照功能实现图片上传(下)

    2017-04-30 17:00

网友点评