Canvas & SVG: Canvas Basics - JUMP START HTML5 (2014)

JUMP START HTML5 (2014)

Chapter 13 Canvas & SVG: Canvas Basics

First of all, let's look at how to create a canvas document. As noted earlier in this book, the canvas element itself looks like this:

<canvas id="MyCanvas" width="300" height="150"></canvas>

HTML5 Canvas Template

Let's start with a basic template that we can use to begin working with. We'll add the canvas element to the page and a small self-executing script that gets the context:

<html>

<head>

<title>Getting started with Canvas</title>

<style type="text/css">

canvas { border: 1px solid black; }

</style>

</head>

<body>

<canvas id="MyCanvas" width="300" height="150"></canvas>

<script>

(function() {

var canvas = document.getElementById('MyCanvas');

if (canvas.getContext){

var ctx = canvas.getContext('2d');

}

}

</script>

</body>

</html>

There are two essential attributes that canvas has: width and height. If the attributes are not specified, then the default of 300px wide by 150px high will be used.

The getElementById function simply finds the canvas element in the DOM, based on the ID we've assigned the canvas, which, in this case, is MyCanvas. The line var ctx = canvas.getContext('2d'); is the 2D context method, which returns an object that exposes the API for the drawing methods we'll use.

Tip: Canvas Element Styling

You can style the canvas element just as you would any other image, using borders, colors, backgrounds, and so on. However, the styling will not affect the actual drawing on the canvas. A canvas without any styling will simply appear as a transparent area.

Drawing a Simple Shape Onto the Canvas

Let's have a look at how we can draw some simple shapes. All drawing must be done in our JavaScript function, after the line var ctx = canvas.getContext('2d');. Let's draw a rectangle:

ctx.fillStyle="#0000FF";

ctx.fillRect(0,0,300,150);

This draws a blue rectangle that fills the canvas area. The fillRect method requires the top-left x and y coordinates of the rectangle to be drawn, followed by its width and height. The code above creates a 300x150px rectangle that is positioned at with its top-left corner at coordinate 0,0 and filled with the current fillStyle, which in this case is a solid blue (#0000FF)—see Figure 13.1. fillStyle can be a color, gradient, or pattern.

Our blue rectangle

Figure 13.1. Our blue rectangle

The canvas 2D API provides methods for drawing several basic shapes, including:

· Rectangles

· Arcs

· Paths

· Text

· Images

W specified the size of the canvas as being 300x150px. If we reduce the rectangle's size, then you'll see that you have a rectangle within the canvas. For example, if we modify the code as follows:

ctx.fillStyle="#0000FF";

ctx.fillRect(0,0,150,75);

A resized rectangle

Figure 13.2. A resized rectangle

The canvas itself remains as a transparent box, as you can see. As we've included a black border around the canvas you can see its area. Without the border you'd see nothing but the blue box, but the canvas would still be there.

Remember that the canvas width and height attributes determine the dimensions of the pixel coordinate system. If you use CSS to specify a different width or height, the canvas image will be squashed or stretched accordingly. For example, if we apply a width of 600px and height of 300px to the canvas in CSS, each canvas 'pixel' would be twice the size of a normal pixel.

Canvas Coordinates and Paths

Canvas uses a two-dimensional coordinates grid. The top-left of the canvas has a coordinate of (0,0). The bottom-right will have a positive x and y coordinate according to the size of the element. In the example above, we used a canvas size of 300x150px, so the bottom-right pixel is at (299,149), because coordinates are zero-based.

Lines are drawn on the canvas using paths. You create paths by using the moveTo() and lineTo() methods, in conjunction with one of the ink methods, stroke() or fill(). moveTo() and lineTo() define the start and end points of the line to be drawn. stroke() draws a shape by "stroking" its outline, while fill() draws a solid shape by filling in the content area of a path.

So, to draw a simple white line through the rectangle we created above:

ctx.strokeStyle = "#FFFFFF";

ctx.beginPath();

ctx.moveTo(0,0);

ctx.lineTo(300,150);

ctx.stroke();

The beginPath method erases any outstanding path drawing operations in preparation for a new path. The stroke() method physically draws the path you've defined. In this case, it's a single line.

Drawing Circles

Now let's look at how we'd draw a circle. The simplest way to do this is to use arc to effectively create a circular path, which can then be used with ink methods, such as stroke() or fill(), like this:

ctx.beginPath();

ctx.arc(95,50,40,0,2*Math.PI);

ctx.stroke();

Here we're using the arc method (which can still be part of a path). The parameters specify the x and y coordinates of the arc's center, the arc's radius, the start angle, and end angle (in radians). Therefore, we've created an arc centered on coordinates 95,50, with a radius of 40 pixels, with a start angle of 0 and an end angle of 2*PI (or 360 degrees). We've used the stroke() method to draw the path, which gives us a circle, as shown in Figure 13.3:

Drawing a circle

Figure 13.3. Drawing a circle

If you added the fill() method, you would end up with a circle that is filled in with the specified color, black by default, as shown in Figure 13.4.

A filled circle

Figure 13.4. A filled circle

Drawing Text

You can draw text onto a canvas using these methods:

· font—defines the font properties

· fillText(text,x,y)—draws text on the canvas

· strokeText(text,x,y)—draws the outline of text on the canvas

Here's an example:

ctx.font = "25px Arial";

ctx.fillText("HTML5 Canvas Rocks!",10,50);

This will draw the words "HTML5 Canvas Rocks!" using block text, using the font Ariel at 25 pixel size, at the coordinates (10,50), as shown in Figure 13.5.

Writing text to the canvas

Figure 13.5. Writing text to the canvas

If you were to replace fillText() now with strokeText(), you would instead have outlined text, as shown in Figure 13.6.

Stroked text

Figure 13.6. Stroked text

You can also add text effects and colors:

ctx.fillStyle= '#0000FF';

ctx.font="Italic 25px Arial";

ctx.fillText("HTML5 Canvas Rocks!",10,50);

This will italicize the text and make it blue, as shown in Figure 13.7.

Blue italic text

Figure 13.7. Blue italic text

Drawing a Triangle

Let's draw a triangle. As there's no built-in triangle shape for us to draw with, we'll need to construct it using paths. To create a basic triangle we can use the following code:

ctx.beginPath();

ctx.moveTo(25,25);

ctx.lineTo(105,25);

ctx.lineTo(25,105);

ctx.fill();

This should appear as shown in Figure 13.8:

A filled triangle

Figure 13.8. A filled triangle

To create a stroked triangle:

ctx.beginPath();

ctx.moveTo(125,125);

ctx.lineTo(125,45);

ctx.lineTo(45,125);

ctx.closePath();

ctx.stroke();

Note the closePath() method; this closes the path by drawing a straight line from the current point to the initial point. This will appear as shown in Figure 13.9:

A stroked triangle

Figure 13.9. A stroked triangle

So that's how to draw basic shapes in HTML5 using the canvas element and JavaScript. Now that you've learned the basics, go and practice with different styles, fonts, and shapes to get further accustomed to using the JavaScript code.

Canvas Sizing

Depending on what you're developing using canvas, you can resize to fit the device being used—if you're needing to fill the screen for say, a game. This can be achieved in a number of ways:

· coding in JavaScript

· using CSS

· CSS transforms using JavaScript

Scaling with JavaScript

var canvas = document.getElementById('canvas');

canvas.width = window.innerWidth;

canvas.height = window.innerHeight;

This will create a canvas which extends to the current viewport size, but you will need to ensure the element has no margin or is affected by other items on the page. In addition, changing the browser window size will not modify the canvas dimensions.

Scaling with CSS

#canvas {

position: relative;

left: 0;

right: 0;

top: 0;

bottom: 0;

margin: auto;

width: 100%;

height: 100%;

}

This changes the size of the canvas box but not the pixel dimensions; the coordinate system remains the same.

CSS Transforms Using JavaScript

var scaleX = canvas.width / window.innerWidth;

var scaleY = canvas.height / window.innerHeight;

var scaleToFit = Math.min(scaleX, scaleY);

canvas.style.transformOrigin = "0 0";

canvas.style.transform = "scale("+scaleToFit+")";

Again, this changes the size of the canvas box, but not the pixel dimensions.