
Cut And
Paste Code For Lesson 6
Simple Bouncing Circle Animation
<!DOCTYPE html>
<html>
<body>
<canvas
id="myCanvas" width="100" height="300" style="border:1px
solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var height = 43;
var move
= 1;
var i = setInterval(function(){
var c =
document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle = "blue";
ctx.beginPath();
ctx.arc(50,height,40,0,2*Math.PI);
ctx.clearRect(0, 0, 100, 300); //rem this out
for illusion
ctx.stroke();
height= height+move;
if (height > 256)
{
// clearInterval(i);
move
= -1
ctx.clearRect(0,
0, 100, 300);
}
if (height < 43)
{
// clearInterval(i);
move
= 1
ctx.clearRect(0,
0, 100, 300);
}
}, 1);
</script>
</body>
</html>
Better Bouncing Circle Animation
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support
the HTML5 canvas tag.</canvas>
<script>
var xpos = 43;
var ypos = 50;
var ymove = 1;
var
xmove = 1;
var i = setInterval(function(){
var c = document.getElementById("myCanvas");
var
ctx = c.getContext("2d");
ctx.strokeStyle = "blue";
ctx.beginPath();
ctx.arc(ypos,xpos,40,0,2*Math.PI);
ctx.clearRect(ypos-43,
xpos-43, 100, xpos+43); //rem this out for illusion
ctx.stroke();
xpos=
xpos+ymove;
ypos = ypos+xmove;
if (xpos > 256)
{
ymove = -1
}
if
(xpos < 43) {
ymove
= 1
}
if (ypos > 455)
{
xmove = -1
}
if
(ypos < 43) {
xmove
= 1
}
}, 1);
</script>
</body>
</html>
Lesson 6 Notes:
More on creating a delay in your program
There are two ways to create a delay:
setTimeout(doSomething,500); // calls doSomething() 500 miliseconds from
now
setInterval(doSomething,500); // calls doSomething() every 500 miliseconds
until stopped
To clear a rectangular
space:
ctx.clearRect(0, 0, 100, 300)
If Else Statements:
<!DOCTYPE html>
<html>
<body>
<button
onclick="myFunction()">Click to compare numbers to 12</button>
<p
id="demo"></p>
<script>
function myFunction()
{
var person = prompt("Enter a number to compare
to 12", "");
if
(person != null) {
if (person < 12) {
document.write("
your number is less than 12");
}
if (person > 12) {
document.write("Your
number is greater than 12");
}
if (person == 12) {
document.write("Trying
to trick me eh!?! Your number IS 12!! :-)");
}
}
}
</script>
</body>
</html>