Android Web Game - Chpt. 2 - Canvas Basic

by Denise Nepraunig

HTML

<canvas id="myCanvas" width="300px" height="300px"></canvas>
<canvas id="mainCanvas" width="300px" height="300px"></canvas>
<canvas id="secondCanvas" width="300px" height="300px"></canvas>
<canvas id="thirdCanvas" width="300px" height="300px"></canvas>
<!-- The stroke is a line; use the half-pixel coordinates when the stroke width is odd and the integer coordinates when it is even, otherwise the line will be blurry and semitransparent. -->

JavaScript

(function () {
    var canvas = document.getElementById('mainCanvas');
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, 300, 300);
    ctx.fillStyle = "lightgray";
    ctx.strokeStyle = "blue";

    ctx.fillRect(50, 50, 100, 120);
    ctx.lineWidth = 3;
    ctx.strokeRect(4.5, 30.5, 70, 70);
}());

// MUAHAHA NOW FINALLY IIFE MAKE SENSE!!!
(function () {
    var canvas = document.getElementById("secondCanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#fffbb3";
    ctx.strokeStyle = "#989681";

    ctx.lineWidth = 2;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.strokeRect(1, 1, canvas.width - 2, canvas.height - 2);

    ctx.beginPath();
    ctx.moveTo(50, 50);
    ctx.lineTo(150, 100);
    ctx.moveTo(200, 200);
    ctx.lineTo(250, 250);
    ctx.strokeStyle = "#000";
    ctx.stroke();

}());

(function () {
    var canvas = document.getElementById("thirdCanvas");
    var ctx = canvas.getContext("2d");
    // For now, set cell size explicitly, later 
    // we will calculate it based on device dimensions 
    var cellSize = 40;
    ctx.beginPath();

    // Drawing horizontal lines 
    for (var i = 0; i < 8; i++) {
        ctx.moveTo(i * cellSize + 0.5, 0);
        ctx.lineTo(i * cellSize + 0.5, cellSize * 6)
    }

    // Drawing vertical lines 
    for (var j = 0; j < 7; j++) {
        ctx.moveTo(0, j * cellSize + 0.5);
        ctx.lineTo(cellSize * 7, j * cellSize + 0.5);
    }

    // Stroking to show them on the screen 
    ctx.lineWidth = 1;
    ctx.strokeStyle = "#989681";
    ctx.stroke();
}());

(function () {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.moveTo(20, 20);
    ctx.bezierCurveTo(20, 100, 200, 100, 200, 20);
    ctx.stroke();
}());