Difference: CanvasActivityIntroCS (2 vs. 3)

Revision 32018-12-11 - JimSkon

Line: 1 to 1
 
META TOPICPARENT name="IntroToCSF2018"

Introduction to Animation with HTML5 and JavaScript

Due: Dev 12
Line: 9 to 9
 
  • HTML5 has a feature called the <canvas> element that allows graphics and animation.
  • Using a programming language called JavaScript, web developers can create graphics, static and moving.
  • Here is an example of a simple animation using HTML5: Bouncing Ball Example
Added:
>
>
 

Step 1 - Draw a ball

  • First we need to create a canvas to draw on.
  • The following code creates a area to "draw" on that is 300 pixels wide, and 300 pixels high:
Line: 101 to 103
 
  • Notice how the balls goes corner to corner. How can we fix that?
  • Let's give the ball a random start point. Let's start by giving the height and width a name for a better program. Then use it to compute a random location at the beginning of the code:
Changed:
<
<
<-- SyntaxHighlightingPlugin -->
var height=300, width=300;
var x=Math.floor(Math.random() * 300);
var y=Math.floor(Math.random() * 300);
<-- end SyntaxHighlightingPlugin -->
>
>
<-- SyntaxHighlightingPlugin -->
var height=300, width=300; var x=Math.random() * 300; var y=Math.random() * 300;
<-- end SyntaxHighlightingPlugin -->
</sticky>
 
  • Let's also now use the height and width in the clearRect function:
%CODE{"javascript"}% context.clearRect(0,0, height, width);
Changed:
<
<
%ENDCODE%
>
>
%ENDCODE%</sticky>
 
  • Next note the ball is going off the edge. How do we fix this? Let's start by making a variable for the radius, and then using that.
%CODE{"javascript"}% var radius=20;
Changed:
<
<
%ENDCODE%
>
>
%ENDCODE%</sticky>
 

Step 5 - Have fun! Add some features!

Line: 126 to 125
 
  • Simulate the effects of gravity and friction (the ball's height decreases with each bounce, and the side to side motion slows down)
  • Whatever you can think of!
Added:
>
>
Random color function:
<-- SyntaxHighlightingPlugin -->
function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
<-- end SyntaxHighlightingPlugin -->
 
META FILEATTACHMENT attachment="Screenshot_20181125_200346.png" attr="" comment="" date="1543194266" name="Screenshot_20181125_200346.png" path="Screenshot_20181125_200346.png" size="2357" user="JimSkon" version="1"
META FILEATTACHMENT attachment="Screenshot_20181125_201215.png" attr="" comment="" date="1543194747" name="Screenshot_20181125_201215.png" path="Screenshot_20181125_201215.png" size="4602" user="JimSkon" version="1"
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2019 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback