html5-canvas-preview
Coding - HTML5

Get Started with HTML5 Canvas

With the HTML5 canvas, you can use JavaScript code to create drawings when the user views your page. These drawings can include animated elements and can even be interactive. You can use the canvas element even if your JavaScript is not advanced, creating shapes, coloring them and positioning them within your page.

In this tutorial we will create a simple canvas drawing using JavaScript. We will draw a gradient, some opaque rectangle shapes and finally some randomly placed circle shapes. The tutorial will act as a foundation for learning to draw using the canvas element and JavaScript.

Create a Page

Start by creating an HTML5 page with a canvas element in it, a script section and some basic styling – use the following outline:

<!DOCTYPE html>
<html>
<head>

<style type="text/css">
div {width:360px; margin:auto; text-align:center;}
canvas {border:2px solid black; margin:auto;}
</style>

<script type="text/javascript">
//scripting
</script>

</head>
<body>
<div>

<canvas id="pic" width="350" height="350">
<!--image for no canvas support-->
<img src="placeholder.png" alt="picture"/>
</canvas>

<input type="button" value="draw" onclick="drawPicture()"/>

</div>
</body>
</html>

Notice the markup we use for the canvas element – it includes an ID so that we can refer to it in JavaScript, together with width and height attributes. Between the opening and closing canvas tags we include a placeholder image to display if the user’s browser does not support the canvas. We apply some basic styling to the page in the style section.

As you can see, we are also using a button input element in the page body – we will draw the picture when the user clicks this button. In the script section in your page head, include the function specified the onClick attribute for the button now:

<script type="text/javascript">
function drawPicture(){
//drawing functions
}
</script>

We will add the drawing code for the tutorial inside this function. When you view the page at first, the canvas element will be empty, drawing only when the button is clicked.

Prepare to Draw

Inside the drawPicture function we added to the page head, start by retrieving a reference to the canvas element using its ID attribute value:

var picCanvas = document.getElementById("pic");

Now we need to check for browser support:

if (picCanvas.getContext){
//we can draw
}

Inside this conditional block we will place the remainder of the code, since we know the user has support. (You could include an else block to do something different when there is no canvas support.) Begin by getting the context:

if (picCanvas.getContext){
	//we can draw
	var picContext = picCanvas.getContext("2d");
	//draw
}

We will use the context object to carry out our drawing operations.

Draw a Gradient Shape

After retrieving the context, create a variable we will use to record the dimensions of the canvas:

var picWidth=350;

Since it is a square in this case we can use the same value for the width and height. Add the following code to set the fill style and draw a rectangle:

picContext.fillStyle = "#000033";
picContext.fillRect(0, 0, picWidth, picWidth);

The fill style is a solid color at the moment, but we will change that soon. We fill a rectangle starting at the top left corner of the canvas and extending its full width and height. Open your page now – you should see a dark blue rectangle when you click the draw button.

Now replace these last two lines of code to make things a little more complex:

var gradient = picContext.createLinearGradient(0, 0, picWidth, picWidth);
gradient.addColorStop(0,"#000033");
gradient.addColorStop(1,"#000066");
picContext.fillStyle = gradient;
picContext.fillRect(0, 0, picWidth, picWidth);

The last two lines are the same apart from the fill style. First, we define a linear gradient, specifying a starting X and Y position of zero and the canvas dimensions. We add two color stops, one a slightly darker blue than the other. Then we apply the gradient as fill style and draw a rectangle with it. Save your page and open it again – this time you should see a gradient filled rectangle rather than a solid color.

Draw in a Loop

We have already seen how you can create a filled rectangle within your canvas, but we can utilize JavaScript to achieve more complex effects. For example, let’s say we wanted to draw opaque rectangles laid on top of one another, running from one corner of the canvas to another. Start by defining how many rectangles we want and what the width of each should be:

var numShapes = 10;
var width = 100;

Now define the starting point for the first rectangle to be drawn at:

var corner = (picWidth-width)/(numShapes-1);

We want the rectangles to be evenly spaced within the canvas, with them all fitting inside it. Now create a loop and draw one rectangle each time the loop iterates:

var i;
for(i=0; i<numShapes; i++){
	picContext.fillStyle = "rgba(255, 255, 255, 0.5)";
	picContext.fillRect(i*corner, i*corner, width, width);
}

Take a moment to understand this code. The fill style is opaque white (50% transparent). Each time, the rectangle is drawn relative to the loop index. Open your page again – you should see the squares staggered across the canvas when you click the button.

html5-canvas-squares

Place Shapes Randomly

Let’s further exploit the features of JavaScript in our drawing operations. This time we will draw small circle shapes in a loop to represent stars, placing each one at a random location within the canvas. Replace the white square drawing code with this new code (or comment the white square drawing code out so that you can still use it as a reference). Start by defining the circle shape radius and a loop:

var radius = 3;
var j;
for(j=0; j<100; j++){ 
//draw stars
}

We will draw 100 stars. This time we are drawing a circle, so we need to use a slightly different process, starting by beginning a path inside the loop:

picContext.beginPath();

Now we need to carry out some processing to ensure that each star is placed within the bounds of the canvas. Add the following to pick minimum and maximum co-ordinates:

var min = radius;
var max = picWidth-radius;

These will be used to pick random X and Y co-ordinates for the center position of each circle. Calculate these co-ordinates now:

var centerX = Math.floor(Math.random() * (max - min + 1)) + min;
var centerY = Math.floor(Math.random() * (max - min + 1)) + min;

The random position will always be within the range specified by the minimum and maximum values. Now use these to define an arc:

picContext.arc(centerX, centerY, radius, 0, 2 * Math.PI);

As well as the center X and Y positions calculated at random, we specify the radius, start angle and end angle. Finally, fill the shape with pale yellow:

picContext.fillStyle = "rgb(255, 255, 100)";
picContext.fill();

Save your file and open it in the browser again. Each time you click the draw button, the stars will be drawn again at random.

html5-canvas-stars

Conclusion

In this tutorial we have explored some of the basic techniques involved in using JavaScript to draw in an HTML5 canvas element. Experiment with the code to try other types of shape. For example, you can include animations and transformations on your drawing elements. As with any HTML5 element, you should test your canvas drawings in as many different types of browser as possible and ensure you include alternative content for users without browser support.

About the author

I'm a developer and technical writer - see benormal.info for details. Follow me on Twitter @BrainDeadAir or email me at [email protected].

Share this post

Leave a Comment

Subscribe To Our Newsletter