[JS|HTML] The Canvas Element

Design, hosting, server-side scripting, software programming
Bookmark and Share

[JS|HTML] The Canvas Element

Postby [DRuG]Nimphious on Sun Jul 13, 2008 5:37 am

One of Apple's better creations. The canvas element basically allows you to draw easily and retroactively on a web page within a certain boundary. One of the best things about this element is it's transparent background, meaning you aren't truly limited to the ugly box form of traditional images.

Implementing the canvas itself is rather simple.

Code: Select all
<canvas id="monkey" width="150" height="150"></canvas>


You do not need to place anything inside the element, as anything inside will be omitted by a standards-compliant browser. However, any browser that does not yet support the element, will simply ignore it and display it's contents. Therefore for backwards compatibility, it's probably a good idea to put something in there along the lines of "Your browser is not capable of displaying this content." or whatever you like.

Anyway, back to the goodies.

You have to give the damn thing an id, that's an id, NOT a name you cronies. This way we can use the getElementById function to find our canvas in our script. That's right, we're using JavaScript, deal'.

Now unfortunately we can only draw in 2D, because the douche-bags that are coding this crap are as slow as you are. But don't worry, drawing stuff on the canvas is extremely easy. It has it's own set of built-in functions for this crap; it's great.

Of course, first you have to tell it you want to draw on it before it's going to let you do anything, so here goes.

Code: Select all
function canvasDraw() {
    var Canvas = document.getElementById('monkey');
    if (Canvas.getContext) {
        var Context = Canvas.getContext('2d');

    }
}
  


Confused yet? Thought so. It's too hard huh.

We create a function to draw something onto our canvas. We call the function canvasDraw. We set the canvas to a variable so we can use it easier (with less code). And finally, we do some cross-browser; Basically if the browser doesn't support canvas, it will ignore our script.

The new Context variable we've made is the drawing surface we'll be using to draw onto the canvas. Basically it's our tool that we will use to draw onto the canvas itself, since we left our pencils at home. Also note that I mentioned earlier, 3D contexts may be implemented later, but for now we'll be using the 2D one.

Simple? No? Too bad, it doesn't get much easier than that really.

Code: Select all
function canvasDraw() {
    var Canvas = document.getElementById('monkey');
    if (Canvas.getContext) {
        var Context = Canvas.getContext('2d');
        Context.fillRect(0, 0, 400, 300);
        Context.fillRect(400, 300, 400, 300);
        Context.clearRect(450, 350, 300, 200);
    }
}
  


Now you should have two black boxes in your canvas, and the right one with a big hole cut out of it.

For those of you who understand how simple this is, and already know the syntax for these functions, and how they work and affect the context, you may skip to the next paragraph. As for the rest of you, I'm very disappointed, really. fillRect is the function used to fill a rectangle on the context, and clearRect is the one used to remove a portion of the canvas and return it to the original transparent state. The syntax is fillRect(x, y, width, height), clearRect(x, y, width, height). Simple enough?

Also note that the clearRect function can be used to clear the canvas, useful for animations. And now for some more functions:

Code: Select all
strokeRect(x, y, width, height) // Same as fillRect, except it only draws the outline.
beginPath() // Lets the context know we want to draw a path
stroke() // Outlines the current path
fill() // Fills the current path            


Those are pretty simple to understand as they are, and require no input variables. But how do we draw paths? you ask. Well I'm getting to that, shut the hell up.

Code: Select all
moveTo(x, y) // Moves the path pointer to the specified location on the context
lineTo(x, y) // Draws a line from the current position of the context pointer,
             // to the specified location, and moves the pointer there
arc(x, y, radius, startAngle, endAngle, anticlockwise)
             // Draws an arc at the location specified using the angles provided
quadraticCurveTo(pnt1x, pnt1y, x, y)
bezierCurveTo(pnt1x, pnt1y, pnt2x, pnt2y, x, y) 


Alright, these functions; arc, moveTo and lineTo, are very easy to use, but can only be used while a path is initiated. Also note that the anticlockwise variable in the arc function is boolean, and specifies the direction in which the arc is drawn from the starting point.

The curves are a little harder, and we won't be covering them in this simple tutorial; but if you're keen to try it anyway, you just specify the end of the curve with the x and y, the start is the pointer, pnt1x and pnt1y specify the quadratic curve's corner point, but on the bezier it's the pointer's handle, and pnt2x/pnt2y are the end point's handle. Play around with them if you're feeling daring.

Now let's try drawing some paths.

Code: Select all
canvasDraw() {
    var Canvas = document.getElementById('monkey');
    if (Canvas.getContext) {
        var Context = Canvas.getContext('2d');
        Context.beginPath();
        var tX, tY, dist;
        for (var i = 0; i < 10; i++) {
            if (% 2 == 0) { dist = 25; } else { dist = 10; }
            tX = 75 + Math.sin(* Math.PI / 5) * dist;
            tY = 75 - Math.cos(* Math.PI / 5) * dist;
            if (== 0) { Context.moveTo(tX, tY); } else { Context.lineTo(tX, tY); }
        }
        Context.fill();
    }
}
 


That will draw us a pretty little 5 pointed black star in the middle of our canvas. Neat huh?

Now let's try an animation...

Code: Select all
var rot = 0;
function canvasDraw() {
    var Canvas = document.getElementById('monkey');
    if (Canvas.getContext) {
        var Context = Canvas.getContext('2d');
        Context.clearRect(0,0,150,150);
        Context.beginPath();
        var tX, tY, dist;
        for (var i = 0; i < 10; i++) {
            if (% 2 == 0) { dist = 25; } else { dist = 10; }
            tX = 75 + Math.sin(* Math.PI / 5 + rot) * dist;
            tY = 75 - Math.cos(* Math.PI / 5 + rot) * dist;
            if (== 0) { Context.moveTo(tX, tY); } else { Context.lineTo(tX, tY); }
        }
        Context.fill();
    }
    if (rot < Math.PI / 2.5) { rot = rot + Math.PI / 100; } else { rot = 0; }
    var t = setTimeout("canvasDraw();", 20);
}
 


And now our pretty little star spins!

Well that was enlightening. And since it's 4:36 in the morning, I think it's about time for some sleep.
User avatar

[DRuG]Nimphious
[DRuG] member
[DRuG] member
 
Posts: 9
Joined: Sun Jul 29, 2007 2:04 pm
Location: Townsville, QLD Australia


Return to Web Design / Programming

Who is online

Users browsing this forum: No registered users and 1 guest

cron