Introduction
In old days of browsers, Flash/Silverlight likes plugins were used to support rich graphics in browsers.
With HTML5, the platform gets native support for the two types rich contents:
- Canvas
- SVG
In this post, our focus will be the Canvas.
I’ll be using Angular for JavaScripting, however the concepts are same if you use some other JS frameworks (React, Vue etc.) or just the plain JavaScript.
The source code is available from the this git repo.
Setup
I will be using an existing angular application and if you are following along this is the same code base from my other angular articles.
Canvas
Canvases are JavaScript based technology. Canvas can be used to create 2D and 3D (WebGL) rasterized images.
Unlike SVGs where we have a mathematical description of the shapes and therefore we can scale them, rasterized images have a set resolution.
Canvases are good choices for animations, game graphics, sketching tools and image manipulation application.
It is lot easier to generate images with canvas, which are difficult to define upfront.
Following are few key points about the HTML-5 canvas:
- An HTML5 canvas is like a real-world canvas, but it is more powerful.
- It can be used for static as well as moving contents (e.g. games).
- Canvas is pixel based, means, you draw pixels on it (so not scalable, contents get fixed size).
- Canvas itself is a simple look-less HTML element (no visual representation on its own).
- All drawings on canvas are done using JavaScript.
- Very often browser allow the GPU of the PC to render the canvas and this is for performance reasons.
Starting with Canvas
To start with I’ve created a component using Angular CLI, this component will encapsulate our demos for canvas:
Following is HTML markup for the canvas component
Canvas element is placed on an HTML page. Setting its size is preferable:
following is the browser UI for canvas
Use JavaScript to work with canvas:
In JavaScript, we first get the canvas by using getElementById
We won’t use canvas directly in code to actually draw on it, instead, we’ll use an intermediate called the context.
With context in hand, we’ll be able to draw on canvas.
Angular way of getting the context
In angular we can get the reference to DOM element using viewChild/TempalateReferenceVariables as follows:
You can check this article to learn about ViewChild and other techniques to access elements in Angular.
To reference the element, we use the TemplateReferenceVariable variable as shown below (notice the #mainCanvas) in the HTML.
Basic Shapes:
Lets draw some basic shapes with JavaScript.
To draw shapes, I have added few buttons to HTML as shown below
Next, let’s add some JavaScript code to click-handlers for these buttons to draw on canvas.
Drawing Basics- Canvas
Canvas has a coordinate system. The point with 0,0 is at the top left.
Simple drawing methods:
fillRect
canvas has simple drawing methods. The above code uses fillRect method to draw a filled rectangle.
- On the context, we first set fill style to a solid color.
- Next, with this style active, we draw a rectangle using the fillRect method, passing in the coordinates (0,0) , width (100) and height (80) pixels.
Here is the output:
strokeRect
This method draw a rectangle with just stroke and no fill.
clearRect
clears a rectangular part of the the canvas.
Drawing Line
We can use lineTo method from canvas API to draw line. Following is the code for drawLine button click handler:
and here is the output
Path
- More Complex shapes than rectangles are drawn using a path.
- A path can be seen as a combination of several sub-paths.
- A sub-path, on the other hand, can be considered as number of points which form a line.
- It is possible to add lines or figures to a sub-path.
To demo this, I have added a button in HTML and its click handler and following is the output and relevant code
Draw a Circle
To draw a circle, we have arc method available:
The method accepts the starting-coordinate (100,100), the radius (60), the start-angle (0) and the end-angle (2*Math.Pi). Both angles are in radians.
Adding Text to Canvas
Text can be add via following methods:
- fillText
- strokeText
output:
Gradients Fills Example
We can also apply gradients while drawing on canvas.
Creating gradients require three steps:
- Creating the gradient.
- Adding color stops.
- Assigning the gradient to the style.
Gradients can be linear or radial.
Output:
Adding Images to Canvas
Canvas can be combined with images for more advanced graphics.
drawImage method can be used for this purpose.
output:
Size can be specified (Resizing):
Zooming is possible:
One way to do is that, before we draw the image, we can scale the context to the desired zoom level:
Transformations in the Canvas
A transformation changes the grid which results in impressive options for the canvas.
For example, we can apply a rotate transform, this will change the angle of the grid, on which we draw. rotate allows to rotate the coordinate system of a number of radians:
and translate, moves the starting point:
in above example, we first used translate method, to move the origin, to the center of the canvas.
Next, we are rotating over 45 degrees.
The we simply draw, but now we are drawing in a changed grid of pixels.
And the result is that the rectangle is rotated and drawn in the center of the canvas.
Scaling the grid is possible
We can also scale the grid system.
we are scaling to Half the size, in vertical position. When we draw, the pixels in the vertical size are scaled to half their original size.
Canvas State
We can store on a stack the current settings of the canvas and can reuse those later.
- save: adds the settings to the stack.
- restore: gets the settings from the stack, replacing current settings.
- Initially, we set fill style to yellow and draw a rectangle.
- we can then call save method, so current settings/state of canvas is stored.
- we then use red, save the red settings.
- we then use blue.
- after that, we want to continue with the settings we had before the blue.
- so, we called the restore method, this pops the blue settings out of the stack and we can continue using the previous one.
Demo – Show Graph of Product Sales
Lets put together what we have learnt into yet another demo. There is a bit of code involved, so I won’t go into those details, but you can check it from the source code to see how it is put together and also change it as per your requirements:
Following are the methods involved
output
Summary
In this post, we covered the basics of HTML-5 canvas and its building blocks which allows us to work with graphics for the web.
You can check the source code available form this git repo.
The deployed sample application is available on this URL.
Let me know if you have some comments or questions. Till next time, Happy coding.