Friday, June 7, 2013

Intro to Template

This blog will cover designs using the JavaScript canvas - useful for web coding.

I have a template set up in an interactive environment over at FiddleSalad, the link is http://fiddlesalad.com/javascript/html-canvas-template/


A couple quick details about the template -
  • The method main() is our entry into the program to keep the code clean and well-formed.
  • I've added a couple of useful methods that you'll find useful such as createBorder() and randomColor() which do what the name implies.  Note that when you use drawCircle() you'll have to include the (x,y,r) dimensions.
  • setInterval() is a time-based method that we'll touch on in later posts.  For now, select entire drawShapes() method and replace with the code given.
For anything else, refer to a beginner Javascript tutorial.  I recommend TheNewBoston.org (->"Tutorials" tab->JavaScript)

Here's a picture of the layout I use, there's a lot of windows that just clutter the screen - just give half of the screen to the "JavaScript" window and the other half to the "Result" window.





var c, w, h;

main();

function main() {

    c = document.getElementById('canvas').getContext('2d');
    h = canvas.height;
    w = canvas.width;

    createBorder();
    drawShapes();
}

function drawShapes() {

    setInterval(function() {

        //=========DRAW HERE=================


    }, 500);
}

function randomColor() {
    switch (Math.floor(Math.random() * 8)) {
    case 0:
        return "yellow";
    case 1:
        return "green";
    case 2:
        return "blue";
    case 3:
        return "red";
    case 4:
        return "orange";
    case 5:
        return "black";
    case 6:
        return "brown";
    case 7:
        return "purple";
    default:
        return "white";
    }
}

function drawCircle(x,y,r) {
    c.beginPath();
    c.arc(x, y, r, 0, Math.PI * 2, true);
    c.fillStyle = "black";
    c.fill();
}

function createBorder() {
    c.moveTo(0, 0);
    c.lineTo(0, h);
    c.lineTo(w, h);
    c.lineTo(w, 0);
    c.lineTo(0, 0);
    c.stroke();
}


No comments: