JS exercise 2 – Canvas intro

This exercise is an intro to <canvas>.

To run, copy-paste into a text editor, save with extension “.html”, and open in a (HTML5 friendly) browser.

<!DOCTYPE html>
<html>
  <head>
    <title>Canvas intro</title>
    <script type="text/javascript">
      function draw(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        context.fillStyle = "rgb(255,0,0)";
        context.fillRect (30,30,100,100);
    	}
    </script>
  </head>
  <body onload="draw();">
    <canvas id="myCanvas" width="300" height="300" style="border:1px solid">
    </canvas>
  </body>
</html>

This line declares the scripting language as JavaScript:

    <script type="text/javascript">

Then we create a function to execute the drawings:

      function draw(){

The next line creates a “canvas” in JavaScript (we can name it as we wish) and associates it with the canvas created in the <body> (IDs must match):

        var canvas = document.getElementById("myCanvas");

The following line creates a 2D context for the canvas, where we will draw:

        var context = canvas.getContext("2d");

The next two lines specify a fill (in red; RGB[A] values from 0 to 255) and draw a rectangle, using parameters (x coordinate, y coordinate, width, height):

        context.fillStyle = "rgb(255,0,0)";
        context.fillRect (30,30,100,100);

Inside the body, the function is triggered upon load (using the onload attribute):

  <body onload="draw();">

Then the canvas is drawn, with a 300 x 300 size and 1 pixel border:

    <canvas id="myCanvas" width="300" height="300" style="border:1px solid">

The result:

Link: http://mlab.taik.fi/mediacode/coursefiles/course_2011_10/2-basic_canvas.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s