×
Namespaces

Variants
Actions

Basics of HTML5 Canvas

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: Maveric (26 Dec 2010)
Last edited: Vaishali Rawat (19 Dec 2012)


Introduction

In this article, first of all I will go through canvas element in principle. Then I will show you how to take it in use and about some principles on using it, what exactly it is and what can you do with it. Then we will go through some thoughts regarding the canvas element and it's usage when talking about more complex and graphically demanding applications, namely games.


1. Canvas Definition

The <canvas> HTML markup language element is the drawing area for graphics for the version HTML5. In this article we will be covering the basic usage of it and some more advanced features of it as well.


2. Typical markup code

Size of the canvas element can be set to a default size, e.g. 360x640 units, which would default to an Nokia N8 mobile device.


         <canvas width="360" height="640"></canvas>

As the drawing area is to be referred later on, we will add an “id” type for it. In this case the name will be “drawboard”. Now every time the canvas needs to be addressed, it can be traced from the DOM by that name. One or more canvases can exist on the same page, and each of them will be appearing in the DOM and also each of the canvases maintain their own state. When the canvas is given an id attribute, they can be accessed like any other element.

Example:

<canvas id=”drawboard” width=”360” height=”640”></canvas>

Now you can easily find and refer to this <canvas> element in the DOM:

var canvas-document.getElementById('drawboard');

The canvas is a 2D drawing context, which is most commonly used with JavaScript. A test bed for canvas actions are online as an application for browser environment, e.g. here:


http://westciv.com/tools/canvasConsole/


Then we would get the canvas with the getContext('2d') and e.g. initialize it with a rectangle as follows:

This would return an object that exposes an API for drawing on the canvas.


    var context-canvas.getContext('2d');
    context.strokeRect(50,50,100,100);


3. Canvas coordinate system

HTML5 canvas element coordinate system is formed so, that the Cartesian system is flipped basically, meaning the origin, x=0, y=0 is located at the top left corner. While we increase the x value, we are going to direction right and if we increase the value y, we will be going downwards.


The HTML5 canvas element resizing is done by the values width and height. Usage of CSS is not required, but could be used.


Above the x axis we can use negative horizontal values even though they will not be visible. The area that will become invisible when the size exceeds the positive value maximum or leaves it with a negative value, will be clipped out automatically.


Canvas element default size is 300x150. Resizing the canvas with width and height is the recommended way. Using CSS the 300x150 element will be resized differently, Left width and height size of the element is 500x500 (not in px), CSS to the right is used with CSS width and height, it is not the same thing. The canvas has been scaled up by CSS, the content is too. So, HTML attributes should be used not CSS.


HTML attributes are numeric values not pixels, the canvas uses coordinate system so all values are numerical values relative to the used coordinate system.


Image below shows the difference between modifying the canvas size with CSS against the default sizing:

File:Will be added soon


Left image attributes, width=”500”, height=”500”,

Right image attributes: CSS properties, width 500px, height 500px


== 4. Basic Drawing ==


The context has properties like, fillStyle, strokeStyle, lineWidth etc. The functions are then used to draw on the context, like fillRect, stroke and so on.


4.1 Rectangles

For drawing rectangles these are the following functions: fill rectangles - context.fillRect

A fill style is needed with context.fillStyle. The context will remember the style until changes.

Fill styles can be:

  • CSS style colors (hex, RGB, RGBa)
  • Gradient objects
  • Pattern objects

Example: color to red

    context.fillstyle=”#f00”
    context.fillstyle=”rgb(255, 0, 0)”
    context.fillstyle=”rgba(255, 130, 0, .6) 
      // semi transparent, in the spirit of CSS.


When the rectangle is drawn, we are using context object's fillRect function. We will specify the left top corner of the rectangle, specify the width and height of it, then apply the current fillstyle or if not set it is defaulting to black fill colour.


Example output:


stroke rectangles – context.strokeRect


For stroke rectangles we use context.strokeStyle to set the style. They can be, like fillStyles described above.


To draw the rectangle we use the method context.strokeRect.


Example:


context.lineWidth=5;

context.strokeStyle=”orange”;

context.strokeRect(25, 25, 75, 50);


Clearing the rectangle we use clearRect, for it need to specify left, top, width, height.Everything underneath will be cleared.


Example:

context.fillRect(0,0,100,100);

        context.clearRect(25, 25, 50,50);


Pattern objects


clear rectangles – context.clearRect

4.2 Lines and paths

Lines do not exist them selves. They are actually paths, they start from somewhere and end somewhere. Then we can specify for the path, what colour they are, gradients and patterns, stroke paths, line width, and define how these lines will join and end.


4.2.1 Line styles

We use context.strokeStyle to set the style:


context.strokeStyle=”#f00” the same manner as with the previous components.


Stroking a path, we start it with


context.beginPath.


With this we move the pen to the start of the line with


context.moveTo and then


draw the actual line with


context.lineTo.


to close the path we will use:


context.Close.


Line width can be specified with lineWidth. We can also specify how lines join with lineJoin, and how it ends with lineCap. Possible values are “bevel”, “round”, “miter”.


Example:


context.beginPath();
context.moveTo(50,50);
context.lineTo(100,100);
context.lineWidth=6;
context.lineCap=”round”;
context.stroke();
context.closePath;

Multiple lines make “objects”. So, in basic canvas API is quite simplified; we will be drawing only rectangles, paths but no circles, ellipses or even lines.


If we do not close the path, we can draw multiples lines in a single path. e.g. triangles can be drawn using this method.


Example:


context.beginPath();
context.moveTo(50,50);
context.lineTo(100,100);
context.lineTo(150,50);
context.lineTo(50,50);
context.stroke();
context.fill();
context.closePath;


Stroke style, when set and use for path and if strokeStyle was not changed it will be used later on.


5. Curved paths, circles, etc.

Api is primitive. For complex components, there are primitives more like


context.arc, context.arcTo

quadraticCurveTo, bezierCurveTo (<-more details!)


Curved paths, circles and other shapes without straigth lines are complex.


5.1 Simple circle

Example:


    context.arc(75, 75, 50, 0, Math.PI*2, true);
    context.fill();


Fills an arc from 0 radians to 2PI radians (360 deg)


    counterclockwise = true;


2PI radians are 360 degrees, the true value just tells the canvas to draw it to counterclockwise direction.


Example:


    var clickMap = [];
    for (var I = 0, n = imageData.length; I < n; I += 4) {
        var row = Math.floor((i /4) / width);
        var col = (i/4) – (row * width);
        if (!clickMap[row]) clickMap[row] - [];
        clickMap[row][col] = imageData[i+3] == 0 7 0 : 1;
    }

6. Canvas in games – notes of performance and usage

When optimizing for web based games, the rendering becomes the most important factor. For example: if an amount of 2000 objects is wanted to be drawn in less than 50 milliseconds, that would need some serious thinking. Such amount of objects could be quite easily in a more comprehensive commercial game concept.


Canvas component is therefore problematic, in that it performs actually slower than HTML. In all the canvas image API in it, is inefficient.


To display the image components, a DOM representation of the image needs to exist first. You need first to load it in JavaScript and then render back to the canvas, which can take an extensive period of time, with a lot of graphics involved. So, for abstract graphics canvas would be quite alright, but with a load of graphics it can be very slow.

This page was last modified on 19 December 2012, at 12:55.
1187 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×