Better Programming

Advice for programmers.

Follow publication

Member-only story

Fun With HTML Canvas: Let’s Create a Star Field

Slawomir Chodnicki
Better Programming
Published in
8 min readDec 14, 2019

In this piece, you’re going to learn how to create the starfield effect embedded above. Yes, it’s running live — it’s not a GIF or video.

I’m only using an HTML canvas. No third-party libraries or advanced math required. I’m using intuitive techniques to make the effect easy to understand and adapt.

The Code

The complete source code for the effect is available here. I suggest you open it in another window and follow along.

The markup for this example is basic. An HTML body and canvas are defined and styled to stretch over the entire browser window.

<!DOCTYPE html>
<meta charset="utf-8" />
<body
style="position: fixed; left: 0px; right: 0px; top: 0px; bottom: 0px; overflow: hidden; margin: 0; padding: 0;"
>
<canvas
id="canvas"
style="width: 100%; height: 100%; padding: 0;margin: 0;"
></canvas>
<script>
...
</script>
</body>

Getting a Handle on Things

If we want to draw anything at all on the canvas, we need to get its DOM element and call getContext("2d") on it. This gives us access to the canvas API.

const canvas = document.getElementById("canvas");
const c = canvas.getContext("2d");

Keeping Track of Window Size

An HTML canvas has its own internal resolution that you set by assigning values to the width and height properties of the context.

We want the canvas to always match the window size, so we set canvas width and height to match. The size of the canvas is useful in calculations later, so we keep that in the w and h variables.

let w;
let h;

const setCanvasExtents = () => {
w = document.body.clientWidth;
h = document.body.clientHeight;
canvas.width = w;
canvas.height = h;
};

setCanvasExtents();

window.onresize = () => {
setCanvasExtents();
};

While we’re at it, we react to window resize events, making sure that the resolution of the canvas always matches the…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (3)

Write a response