Canvas- Moving Ball and Wall Hit Reflection

Written by @m_k_amin 2 July 2013

One of the simplest examples of moving objects is a moving ball and surrounding walls. When it hits the walls, the wall reflects it and the direction of the ball movement changes. Realizing this example is so useful for beginners who want to start creating animations by coding. HTML5 Canvas and Javascript can also be used for creating animated objects. The following example shows how to create moving ball with HTML5 Canvas.

Code Snippet:

                                                
                                                <!-- this script is provided by www.html5freecode.com coded by: Kerixa Inc. -->
<!-- This Script is from www.html5freecode.com, Coded by: Kerixa Inc-->
<canvas id="myCanvas" width="400" height="230"></canvas>
<script>
    var cnv = document.getElementById('myCanvas')
    var ctx = cnv.getContext('2d')
    var deg = Math.PI/180
	var spx,spy,x,y
	
    var LinGrad= ctx.createLinearGradient(20, 20, 400, 230)
	LinGrad.addColorStop(0, "rgb(15, 255, 140)")
	LinGrad.addColorStop(0.33, "rgb(15, 240, 255)")
	LinGrad.addColorStop(0.66, "rgb(250, 200, 20)")	
	LinGrad.addColorStop(1, "rgb(165, 20, 250)")
	
	spx=3;	spy=-3
	x=200;	y=150
    ctx.beginPath()
    ctx.shadowBlur = 3
	ctx.shadowColor= "rgba(100,100,100,.4)"
	ctx.shadowOffsetX = ctx.shadowOffsetY = 4
    ctx.strokeStyle= "blue"	
	ctx.lineWidth=5
	ctx.strokeRect(10,10,380,210)
	ctx.fillStyle= LinGrad
	ctx.closePath()
	setInterval(DrawAll, 33)	
	
function DrawAll(){
	ctx.beginPath()
	if (x>=370 || x<=29) spx=-spx
	if (y>=200 || y<=29) spy=-spy
	x=x+spx
	y=y+spy
	ctx.clearRect(0,0,400,300)
	ctx.arc(x,y,15,0,Math.PI*2,true)
	ctx.fill()
	ctx.strokeRect(10,10,380,210)	
	ctx.closePath()
}

</script>
<div style="text-align: left"><font face="Tahoma"><br><a target="_blank" href="http://www.html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div>
<a target='_blank' href='www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                
                                            

Example:


About @m_k_amin

This user is pending a biography.

M
TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members:
advertisement 2