Subscribe

Vanilla JavaScript colouring our canvas elements 🌈

✍️

Adding some colour to our canvas art

16 Sep, 2020 Β· 2 min read

So far, we have learned the basics of the canvas and how to export it as an image. But it was all plain looking, so let’s go ahead and explore our coloring options for the canvas.

Today we’ll learn how to make the following;

See the Pen Vanilla JavaScript colouring our canvas elements 🌈 - transparency by Chris Bongers (@rebelchris) on CodePen.

Option for coloring

We have been using fillRect and stroke options. If we want to add color to this, we can use the following two options:

  • fillStyle => Colour for the inside of our element
  • strokeStyle => Colour for the stroke

Let’s say we want to make our block purple. All these options will result in the same result:

ctx.fillStyle = 'purple';
ctx.fillStyle = '#800080';
ctx.fillStyle = 'rgb(128, 0, 128)';
ctx.fillStyle = 'rgba(128, 0, 128, 1)';

Let’s try this out on our basic square in Codepen.

See the Pen Vanilla JavaScript colouring our canvas elements 🌈 - FillStyle by Chris Bongers (@rebelchris) on CodePen.

The same can be used for our strokeStyle as such:

ctx.strokeStyle = 'purple';
ctx.strokeStyle = '#800080';
ctx.strokeStyle = 'rgb(128, 0, 128)';
ctx.strokeStyle = 'rgba(128, 0, 128, 1)';

And that will result in the following Codepen.

See the Pen Vanilla JavaScript colouring our canvas elements 🌈 - StrokeStyle by Chris Bongers (@rebelchris) on CodePen.

Using transparency on canvas elements

The cool part you might have spotted is the rgba method.

We can set our transparency and have overlapping elements like this:

ctx.fillStyle = 'rgba(46, 196, 182, 0.5)';
ctx.fillRect(25, 25, 100, 100);

ctx.fillStyle = 'rgba(231, 29, 54, 0.5)';
ctx.fillRect(75, 75, 100, 100);

This will result in the following Codepen.

See the Pen Vanilla JavaScript colouring our canvas elements 🌈 - transparency by Chris Bongers (@rebelchris) on CodePen.

Browser Support

The canvas element is well supported these days and is defiantly a good option if you want to draw vectors on screen.

HTML Canvas support

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

Removing all vowels with JavaScript

3 Dec, 2022 Β· 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 Β· 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter