Tuesday, 2 September 2014

HTML5 - Mastering the Canvas Element (IV) - Colours and Gradients!


Who doesn't like colour? If you noticed carefully, all of your drawings were plain black-n-white. In this tutorial, we learn to draw graphics with colour. From as simple as solid colours, to as complicated as gradients, we'll cover everything in this tutorial.

In the end, we'll also learn to use the erasing functionality of canvas.

Adding colour

This is really simple. We have two options, changing the border colour and the fill colour. And here's how you do it:
context.fillStyle="red"; // Changing the fill colour
context.strokeStyle="red"; // Changing the stroke colour

Adding gradients

Solid colours might be pretty boring. So, here we are, learning about gradients. To start creating a gradient, we'll first have to create a variable to hold the gradient. To do so, we use the createLinearGradient. This function takes in 4 parameters, which are exactly the same as the fillRect and strokeRect functions.
var gradient = context.getLinearGradient(0, 0, 100, 100);
Now that we have a gradient variable, we can start adding colour to it. To add colour, we use the addColorStop function.

This function takes in two parameters. The second one specifies the colour and the first one specifies, where the colour will start and end. The first parameter is a value between 0 and 1.

If you didn't understand what the first parameter does, I totally understand. The best way to understand how something works in computer science, is to experiment with it, try different values and observe the change, and I really encourage you to do it.

After you create a gradient variable and add colours to it. You can use it to fill objects by setting the fillStyle property of the context to the gradient variable.

Here's an example to draw a square with a gradient:
var gradient = context.getLinearGradient(0, 0, 100, 100);
gradient.addColorStop(0.0, "red");
gradient.addColorStop(1.0, "red");
context.fillStyle = gradient;
context.fillRect(0 ,0 , 100, 100);

That's all folks!

Okay, we got something else to cover that I will throw into the next tutorial in order to adhere to my not-to-stuff-too-much-technical-content-in-one-post policy.

You already know to draw rectanglescircles and arcs in canvas . But with what we'll learn in the next tutorial, you'll be able to draw virtually every shape that possibly exists!

No comments:

Post a Comment