- Getting Started with HTML5 Canvas
- How to use HTML5 Canvas
- Creating a HTML5 Canvas with Javascript
- Remember Javascript Order
- Drawing on our canvas
- Output of this code:
- Drawing Multiple Shapes with HTML5 Canvas
- Conclusion
- HTML Canvas Tutorial
- What is HTML Canvas?
- HTML Canvas Can Draw Text
- HTML Canvas Can Draw Graphics
- HTML Canvas Can be Animated
- HTML Canvas Can be Interactive
- HTML Canvas Can be Used in Games
- Canvas Example
- Example
- See Also:
- Browser Support
- HTML SVG Graphics
- Browser Support
- SVG Circle
- Example
- SVG Rectangle
- Example
- SVG Rounded Rectangle
- Example
- SVG Star
- Example
- SVG Logo
- Example
- Differences Between SVG and Canvas
- Comparison of Canvas and SVG
- SVG Tutorial
Getting Started with HTML5 Canvas
HTML canvas is the easiest way to create graphics in Javascript and HTML. You may see it also written as HTML5 Canvas, as it is strongly associated with the shift to HTML5. HTML Canvas can be hard to get the hang of. If you agree, you’re not alone. So in this guide let’s go through the basics of HTML canvas, and how you can use it.
How to use HTML5 Canvas
To start with HTML5 Canvas, we need to create a
id="myCanvas" width="400" height="200">
You may often see canvas with predefined width and height, which is useful if the graphic we’re producing has to have a certain size. You could set your canvas to be of width and height 100%, too. That’s all you need to do on the HTML side of things. Let’s look at how we can initiate a basic canvas which we can start to produce graphics on.
Creating a HTML5 Canvas with Javascript
- 2d — a 2 dimensional context for rendering 2d graphics on.
- webgl — a 3 dimensional context for rendering 3d objects on.
- bitmaprenderer — only allows us to replace the canvas context with something that is a BitImage.
Although all of these are useful, for most canvas work, we use 2d. So let’s start by selecting our canvas element, and applying the correct context:
let myCanvas = document.getElementById('myCanvas'); // Set the context of our canvas let context = myCanvas.getContext('2d');
Above, we now have a variable, context, which we can use to draw graphics on our canvas. Although I’ve called this variable context, it is common to see it named ctx instead.
Remember Javascript Order
If you are having trouble getting this to work, make sure your Javascript is after your element. The HTML element needs to exist before we can select it!
Drawing on our canvas
Now we have our context, we can start to draw on it. HTML canvas has a number of different ways to draw. Let’s look at a basic example — creating a rectangle.
let myCanvas = document.getElementById('myCanvas'); // Set the context of our canvas let context = myCanvas.getContext('2d'); // Begin drawing something on the context context.beginPath(); // Draw a rectangle using the rect() function context.rect(188, 50, 200, 100); // Fill our rectangle context.fillStyle = '#13caa7'; context.fill(); // Add a border to our rectangle context.lineWidth = 5; context.strokeStyle = 'white'; context.stroke(); // Finish our rectangle context.closePath();
Output of this code:
As you can see, HTML canvas drawing can become quite verbose quite quickly. Let’s break down the code section by section after creating our context:
context.beginPath()
We begin any new shape or drawing on a canvas with beginPath(). This lets us split out the information on one shape, versus the next.
context.rect(10, 10, 100, 120)
This is a standard shape function, the arguments of which are x, y, width, height. The above code then creates a rectangle 10px from the top and 10px from the left, of width 100px and height 120px.
context.fillStyle, context.fill()
The first line, fillStyle, sets the color, and then fill the shape itself with the function fill().
context.lineWidth, strokeStyle, stroke()
These should look familiar to the last section — we set the pixel width of the border with lineWidth, then the color with strokeWidth, and action the stroke with stroke().
context.closePath()
Our rectangle is now done — we finish it off by using the closePath() function. Now that we’ve closed our path, we are free to create more shapes if we like.
Drawing Multiple Shapes with HTML5 Canvas
Since we’re using Javascript, we can programmatically draw shapes with canvas. For example, we can use a while loop to draw many rectangles, all beside each other:
The code for this follows the same concepts as we followed before — the only difference is that we are using a while() loop to reiteratively draw more rectangles until the canvas is full:
Using a while loop in HTML5 Canvas:
let myCanvas = document.getElementById('myCanvas'); // Set the context of our canvas let context = myCanvas.getContext('2d'); // Draw a rectangle using the rect() function let startX = 10; let startY = 10; let rectWidth = 100; let rectHeight = 100; while(startY newCanvas.height) // Begin drawing something on the context context.beginPath(); // Draw our canvas context.rect(startX, startY, rectWidth, rectHeight); // Fill our rectangle context.fillStyle = '#13caa7'; context.fill(); // Add a border to our rectangle context.lineWidth = 5; context.strokeStyle = 'white'; context.stroke(); // Finish our rectangle context.closePath(); startX += rectWidth + 10; console.log(startX, startY, newCanvas.width, newCanvas.height) if(startX > newCanvas.width - 100) startX = 10; startY += rectHeight + 10; > if(startY > newCanvas.height - 100) startX = newCanvas.width + 50; startY = newCanvas.height + 50; > >
Conclusion
In this introduction, we’ve looked at how HTML5 canvas can be created, and how you can draw basic shapes onto it. We’ve covered how you can reiteratively draw on the canvas through Javascript, by using a while loop. Using this as a base, you’ll be able to experiment and try out even more. I hope you’ve enjoyed this article.
HTML Canvas Tutorial
The HTML element is used to draw graphics on a web page.
The graphic above is created with .
It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor text.
What is HTML Canvas?
The HTML element is used to draw graphics, on the fly, via scripting (usually JavaScript).
The element is only a container for graphics. You must use a script to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
HTML Canvas Can Draw Text
Canvas can draw colorful text, with or without animation.
HTML Canvas Can Draw Graphics
Canvas has great features for graphical data presentation with an imagery of graphs and charts.
HTML Canvas Can be Animated
Canvas objects can move. Everything is possible: from simple bouncing balls to complex animations.
HTML Canvas Can be Interactive
Canvas can respond to JavaScript events.
Canvas can respond to any user action (key clicks, mouse clicks, button clicks, finger movement).
HTML Canvas Can be Used in Games
Canvas’ methods for animations, offer a lot of possibilities for HTML gaming applications.
Canvas Example
In HTML, a element looks like this:
The element must have an id attribute so it can be referred to by JavaScript.
The width and height attribute is necessary to define the size of the canvas.
Tip: You can have multiple elements on one HTML page.
By default, the element has no border and no content.
To add a border, use a style attribute:
Example
The next chapters show how to draw on the canvas.
See Also:
Browser Support
The element is an HTML5 standard (2014).
is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
HTML SVG Graphics
The HTML element is a container for SVG graphics.
SVG has several methods for drawing paths, boxes, circles, text, and graphic images.
Browser Support
The numbers in the table specify the first browser version that fully supports the element.
Element | |||||
---|---|---|---|---|---|
4.0 | 9.0 | 3.0 | 3.2 | 10.1 |
SVG Circle
Example
SVG Rectangle
Example
SVG Rounded Rectangle
Example
SVG Star
Sorry, your browser does not support inline SVG.
Example
SVG Logo
Sorry, your browser does not support inline SVG.
Example
Differences Between SVG and Canvas
SVG is a language for describing 2D graphics in XML. Canvas draws 2D graphics, on the fly (with a JavaScript). SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element. In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape. Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.
Comparison of Canvas and SVG
- Resolution dependent
- No support for event handlers
- Poor text rendering capabilities
- You can save the resulting image as .png or .jpg
- Well suited for graphic-intensive games
- Resolution independent
- Support for event handlers
- Best suited for applications with large rendering areas (Google Maps)
- Slow rendering if complex (anything that uses the DOM a lot will be slow)
- Not suited for game applications
SVG Tutorial
To learn more about SVG, please read our SVG Tutorial.