will.institute

by Will Lesieutre

Canvas Basics

I want to paint with javascript, so the first thing I need is a <canvas>. It’s an HTML element with a rendering context, and anything drawn in the rendering context is displayed inside the canvas element.

A canvas only needs a couple of properties: an id so that the element can be referenced from javascript, and a width and height so it knows how large it should be. Here’s a 200x200 square canvas:

<canvas id="firstCanvas" width="200" height="200"></canvas>

It doesn’t look like anything because it starts with an empty rendering context. But that’s easy to change; the script below draws a box to fill it with a solid color:

function fillCanvas(color) {
    const canvas = document.getElementById("firstCanvas");
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = color;
    ctx.fillRect(0,0,canvas.width,canvas.height);
}

Let’s Draw

Filling a solid color is great, but let’s kick things up a notch and make a triangle.

In the first example, there was a fillRect function to draw a filled rectangle. Canvas doesn’t have a built in function for other polygons, so to display a triangle I’ll have to make it myself. A triangle can be drawn as a “path” - a series of lines and arcs from one point to the next. I’ll pick a start point, draw lines to two more points, and then close the path back to the first point:

<canvas id="triCanvas" width="200" height="200"></canvas>

function drawTriangle(color) {
    const canvas = document.getElementById("triCanvas");
    const ctx = canvas.getContext("2d");
    ctx.lineWidth = 10;
    ctx.strokeStyle = color;
    ctx.moveTo(100, 40);
    ctx.lineTo(180, 170);
    ctx.lineTo(20, 170);
    ctx.closePath();
    ctx.stroke();
}

That’s the Basics

But there’s plenty of room for improvement. If you’re on a high DPI screen you may notice the triangle’s edges look pixelated. And it’s an awfully small canvas, especially if you’re reading on a large screen. Next up, I’ll dive into rendering canvases at different sizes.