19 October 2021

Hit the canvas

The Canvas element allows you to create a surface that JavaScript can draw on. Download the sample code at the left.

Here is your HTML file. The canvas element is not self-closing. Inside, put an error message for people with superduperultra ancient browsers. You must specify its height and width when you create it.


<!doctype html>
<!--Author: Morrison-->

<html lang="en">
<head>
<title>canvasExample</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="canvasExample.css"/>
<script src="canvasExample.js">
</script>
</head>
<body>
<h2>Canvas Example</h2>

<canvas height="500" width="800" id="surface">
    <p>Get a modern browser that supports canvas, chumley!</p>
</canvas>
</body>
</html>

By nature, a canvas is an inline element. Let's make it block-level and center it. I included a border so you can see it in its empty state on the screen.


/*Author: Morrison*/
h1, h2, .display
{
    text-align:center;
}
canvas
{
    border:solid 1px black;
    display:block;
    margin-left:auto;
    margin-right:auto;
}

Any graphics that appear are created by JavaScript.


/*Author: Morrison*/
window.addEventListener("load", main);
function main()
{
}

With these three files you are ready to go.

Let's wire up the canvas so you are ready to draw and run a little test to see if it's in working order..

A Canvas Puzzler

Go into the W3Schools Canvas Tutorial. See if you can create this little scene.

picture of a canvas puzzler exercise

Here is some basic stuff ewe knead 2 no about. You can deduce colors using Firefox's eyedropper.

Drawing Paths

Draw A Triangle