Tip: also check my tutorials how to print a canvas to a data URL, how to write text into to an HTML canvas, how to load an image in an HTML canvas and how to create and save an image with Node.js and Canvas
The HTML canvas is an HTML tag, <canvas>
, which is an element where we can draw to using the Canvas API.
Create a canvas
Creating a canvas is as simple as dropping a <canvas></canvas>
in a blank HTML file:
You don’t see anything in the page because the canvas is an invisible element. Let’s add some border:
Chrome automatically adds an 8px margin to the body
element. This is why our border looks like a frame, and you can remove that margin by setting
body {
margin: 0;
}
We’ll leave the default for now.
Our canvas is now reachable from JavaScript using the DOM Selectors API, so we can use document.querySelector()
:
const canvas = document.querySelector('canvas')
Change the background color of a canvas
You do that in CSS:
canvas {
background-color: lightblue;
}
Resize a canvas
You can set the width and height in CSS:
canvas {
border: 1px solid black;
width: 100%;
height: 100%;
}
and in this way the canvas will expand to fill all the outer element size.
If you put the canvas as a first level element in the HTML, the above code will expand the canvas to fit the entire body.
The body is not filling the entire window size. To fill the entire page instead we need to use JavaScript:
canvas.width = window.innerWidth
canvas.height = window.innerHeight
If you now remove the body margin and set the background of the canvas using CSS, we can fill our entire page with the canvas and we can start drawing on it:
If the window resizes we need to recalculate the canvas width as well, using a debounce to avoid calling too many times our canvas resizing (the resize
event can be called hundreds of times as you move the window with the mouse, for example):
const debounce = (func) => {
let timer
return (event) => {
if (timer) { clearTimeout(timer) }
timer = setTimeout(func, 100, event)
}
}
window.addEventListener('resize', debounce(() => {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
}))
Get a context from the canvas
We want to draw to the canvas.
To do this, we need to get a context:
const c = canvas.getContext('2d')
Some assign the context to a variable named
c
, somectx
- it’s a common way to shortcut “context”
The getContext()
method returns a drawing context on the canvas, according to the type that you pass as parameter.
Valid values are
2d
, the one we’ll usewebgl
to use WebGL version 1webgl2
to use WebGL version 2bitmaprenderer
to use with ImageBitmap
Based on the context type, you can pass a second parameter to getContext()
to specify additional options.
In the case of the 2d
context, we basically have one parameter we can use in all browsers, and it’s alpha
, a boolean that defaults to true. If set to false, the browser knows the canvas does not have a transparent background and can speed up rendering.
Draw elements to a canvas
With the context we can now draw elements.
We have several methods to do so. We can draw:
- text
- lines
- rectangles
- paths
- images
and for each of those elements we can alter the fill, the stroke, the gradient, the pattern, the shadow, rotate them, scale and perform a lot of operations.
Let’s start with the simplest thing: a rectangle.
The fillRect(x, y, width, height)
method serves this purpose:
c.fillRect(100, 100, 100, 100)
This is going to draw a black rectangle of 100 x 100 pixels, starting from position x 100 and y 100:
You can color the rectangle by using the fillStyle()
method, passing any valid CSS color string:
c.fillStyle = 'white'
c.fillRect(100, 100, 100, 100)
You can get creative now and draw many things in this way:
for (let i = 0; i < 60; i++) {
for (let j = 0; j < 60; j++) {
c.fillStyle = `rgb(${i * 5}, ${j * 5}, ${(i+j) * 50})`
c.fillRect(j * 20, i * 20, 10, 10)
}
}
or
for (let i = 0; i < 60; i++) {
for (let j = 0; j < 60; j++) {
c.fillStyle = `rgb(${i * 5}, ${j * 5}, ${(i+j) * 50})`
c.fillRect(j * 20, i * 20, 20, 20)
}
}
Drawing elements
As mentioned you can draw many things:
- text
- lines
- rectangles
- paths
- images
Let’s just see a few of them, rectangles and text, to get the gist of how things work. You can find the API for all the rest that you need here.
Changing the colors
Use the fillStyle
and strokeStyle
properties to change the fill and stroke colors of any figure. They accept any valid CSS color, including strings and RGB calculations:
c.strokeStyle = `rgb(255, 255, 255)`
c.fillStyle = `white`
Rectangles
You have 3 methods:
- clearRect(x, y, width, height)
- fillRect(x, y, width, height)
- strokeRect(x, y, width, height)
We saw fillRect()
in the previous section. strokeRect()
is similar in how it’s called, but instead of filling a rect, it just draws the stroke using the current stroke style (which can be changed using the strokeStyle
context property):
const c = canvas.getContext('2d')
for (let i = 0; i < 61; i++) {
for (let j = 0; j < 61; j++) {
c.strokeStyle = `rgb(${i * 5}, ${j * 5}, ${(i+j) * 50})`
c.strokeRect(j * 20, i * 20, 20, 20)
}
}
clearRect()
sets an area as transparent:
Text
Drawing text is similar to rectangles. You have 2 methods
- fillText(text, x, y)
- strokeText(text, x, y)
which let you write text on the canvas.
x
and y
refer to the bottom-left corner.
You change the font family and size using the font
property of the canvas:
c.font = '148px Courier New'
There are other properties you can change, related to text (* = default):
textAlign
(start*, end, left, right, center)textBaseline
(top, hanging, middle, alphabetic*, ideographic, bottom)direction
(ltr, rtl, inherit*)
Lines
To draw a line you first call the beginPath()
method, then you provide a starting point with moveTo(x, y)
, and then you call lineTo(x, y)
to make the line to that new coordinates set. You finally call stroke()
:
c.beginPath()
c.moveTo(10, 10)
c.lineTo(300, 300)
c.stroke()
The line is going to be colored according to the c.strokeStyle
property value.
A more complex example
This code creates a canvas that generates 800 circles:
Every circle is perfectly contained in the canvas, and its radius is randomized.
Any time you resize the window, the elements are regenerated.
You can play around with on Codepen.
const canvas = document.querySelector('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
const c = canvas.getContext('2d')
const circlesCount = 800
const colorArray = [
'#046975',
'#2EA1D4',
'#3BCC2A',
'#FFDF59',
'#FF1D47'
]
const debounce = (func) => {
let timer
return (event) => {
if (timer) { clearTimeout(timer) }
timer = setTimeout(func, 100, event)
}
}
window.addEventListener('resize', debounce(() => {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
init()
}))
const init = () => {
for (let i = 0; i < circlesCount; i++) {
const radius = Math.random() * 20 + 1
const x = Math.random() * (innerWidth - radius * 2) + radius
const y = Math.random() * (innerHeight - radius * 2) + radius
const dx = (Math.random() - 0.5) * 2
const dy = (Math.random() - 0.5) * 2
const circle = new Circle(x, y, dx, dy, radius)
circle.draw()
}
}
const Circle = function(x, y, dx, dy, radius) {
this.x = x
this.y = y
this.dx = dx
this.dy = dy
this.radius = radius
this.minRadius = radius
this.color = colorArray[Math.floor(Math.random() * colorArray.length)]
this.draw = function() {
c.beginPath()
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
c.strokeStyle = 'black'
c.stroke()
c.fillStyle = this.color
c.fill()
}
}
init()
Another example: animating elements on the canvas
Based on the example above, we animate the elements using a loop. Every circle has its own “life” and moves within the borders of the canvas. When the border is reached it bounces back:
See the Pen HTML Canvas fun with circles, not interactive by Flavio Copes (@flaviocopes) on CodePen.
We achieve this by using requestAnimationFrame()
and slightly moving the image at every frame rendering iteration.
Interact with the elements on the canvas
Here is the above example expanded to let you interact with the circles using the mouse.
When you hover the canvas, the items near your mouse will increase in size, and they will return back to normal when you move somewhere else:
See the Pen HTML Canvas fun with circles by Flavio Copes (@flaviocopes) on CodePen.
How does it work? Well, first I track the mouse position using 2 variables:
let mousex = undefined
let mousey = undefined
window.addEventListener('mousemove', (e) => {
mousex = e.x
mousey = e.y
})
Then we use those variables inside the update() method of Circle, to determine if the radius should increase (or decrease):
if (mousex - this.x < distanceFromMouse && mousex - this.x > -distanceFromMouse && mousey - this.y < distanceFromMouse && mousey - this.y > -distanceFromMouse) {
if (this.radius < maxRadius) this.radius += 1
} else {
if (this.radius > this.minRadius) this.radius -= 1
}
distanceFromMouse
is a value expressed in pixels (set to 200) that defines how far we want the circles to react to the mouse.
Performance
If you try to edit those projects above and add a bunch more circles and moving parts, you’ll probably notice performance issues. Browsers consume a lot of energy to render the canvas with animations and interactions, so pay attention so that the experience is not ruined on less performant machines than yours.
In particular I had issues when trying to create a similar experience with emojis rather than circles, and I found that text takes a lot more power to render, and so it was sluggish pretty quickly.
See the Pen HTML Canvas fun with Emojis by Flavio Copes (@flaviocopes) on CodePen.
This page on MDN lists many performance tips.
Closing words
This was just an introduction to the possibilities of Canvas, an amazing tool that you can use to create incredible experiences on your web pages.
Download my free JavaScript Beginner's Handbook
More js tutorials:
- Things to avoid in JavaScript (the bad parts)
- Deferreds and Promises in JavaScript (+ Ember.js example)
- How to upload files to the server using JavaScript
- JavaScript Coding Style
- An introduction to JavaScript Arrays
- Introduction to the JavaScript Programming Language
- The Complete ECMAScript 2015-2019 Guide
- Understanding JavaScript Promises
- The Lexical Structure of JavaScript
- JavaScript Types
- JavaScript Variables
- A list of sample Web App Ideas
- An introduction to Functional Programming with JavaScript
- Modern Asynchronous JavaScript with Async and Await
- JavaScript Loops and Scope
- The Map JavaScript Data Structure
- The Set JavaScript Data Structure
- A guide to JavaScript Template Literals
- Roadmap to Learn JavaScript
- JavaScript Expressions
- Discover JavaScript Timers
- JavaScript Events Explained
- JavaScript Loops
- Write JavaScript loops using map, filter, reduce and find
- The JavaScript Event Loop
- JavaScript Functions
- The JavaScript Glossary
- JavaScript Closures explained
- A tutorial to JavaScript Arrow Functions
- A guide to JavaScript Regular Expressions
- How to check if a string contains a substring in JavaScript
- How to remove an item from an Array in JavaScript
- How to deep clone a JavaScript object
- Introduction to Unicode and UTF-8
- Unicode in JavaScript
- How to uppercase the first letter of a string in JavaScript
- How to format a number as a currency value in JavaScript
- How to convert a string to a number in JavaScript
- this in JavaScript
- How to get the current timestamp in JavaScript
- JavaScript Strict Mode
- JavaScript Immediately-invoked Function Expressions (IIFE)
- How to redirect to another web page using JavaScript
- How to remove a property from a JavaScript object
- How to append an item to an array in JavaScript
- How to check if a JavaScript object property is undefined
- Introduction to ES Modules
- Introduction to CommonJS
- JavaScript Asynchronous Programming and Callbacks
- How to replace all occurrences of a string in JavaScript
- A quick reference guide to Modern JavaScript Syntax
- How to trim the leading zero in a number in JavaScript
- How to inspect a JavaScript object
- The definitive guide to JavaScript Dates
- A Moment.js tutorial
- Semicolons in JavaScript
- The JavaScript Arithmetic operators
- The JavaScript Math object
- Generate random and unique strings in JavaScript
- How to make your JavaScript functions sleep
- JavaScript Prototypal Inheritance
- JavaScript Exceptions
- How to use JavaScript Classes
- The JavaScript Cookbook
- Quotes in JavaScript
- How to validate an email address in JavaScript
- How to get the unique properties of a set of objects in a JavaScript array
- How to check if a string starts with another in JavaScript
- How to create a multiline string in JavaScript
- The ES6 Guide
- How to get the current URL in JavaScript
- The ES2016 Guide
- How to initialize a new array with values in JavaScript
- The ES2017 Guide
- The ES2018 Guide
- How to use Async and Await with Array.prototype.map()
- Async vs sync code
- How to generate a random number between two numbers in JavaScript
- HTML Canvas API Tutorial
- How to get the index of an iteration in a for-of loop in JavaScript
- What is a Single Page Application?
- An introduction to WebAssembly
- Introduction to JSON
- The JSONP Guide
- Should you use or learn jQuery in 2020?
- How to hide a DOM element using plain JavaScript
- How to merge two objects in JavaScript
- How to empty a JavaScript array
- How to encode a URL with JavaScript
- How to set default parameter values in JavaScript
- How to sort an array of objects by a property value in JavaScript
- How to count the number of properties in a JavaScript object
- call() and apply() in JavaScript
- Introduction to PeerJS, the WebRTC library
- Work with objects and arrays using Rest and Spread
- Destructuring Objects and Arrays in JavaScript
- The definitive guide to debugging JavaScript
- The TypeScript Guide
- Dynamically select a method of an object in JavaScript
- Passing undefined to JavaScript Immediately-invoked Function Expressions
- Loosely typed vs strongly typed languages
- How to style DOM elements using JavaScript
- Casting in JavaScript
- JavaScript Generators Tutorial
- The node_modules folder size is not a problem. It's a privilege
- How to solve the unexpected identifier error when importing modules in JavaScript
- How to list all methods of an object in JavaScript
- The String replace() method
- The String search() method
- How I run little JavaScript snippets
- The ES2019 Guide
- The String charAt() method
- The String charCodeAt() method
- The String codePointAt() method
- The String concat() method
- The String endsWith() method
- The String includes() method
- The String indexOf() method
- The String lastIndexOf() method
- The String localeCompare() method
- The String match() method
- The String normalize() method
- The String padEnd() method
- The String padStart() method
- The String repeat() method
- The String slice() method
- The String split() method
- The String startsWith() method
- The String substring() method
- The String toLocaleLowerCase() method
- The String toLocaleUpperCase() method
- The String toLowerCase() method
- The String toString() method
- The String toUpperCase() method
- The String trim() method
- The String trimEnd() method
- The String trimStart() method
- Memoization in JavaScript
- The String valueOf() method
- JavaScript Reference: String
- The Number isInteger() method
- The Number isNaN() method
- The Number isSafeInteger() method
- The Number parseFloat() method
- The Number parseInt() method
- The Number toString() method
- The Number valueOf() method
- The Number toPrecision() method
- The Number toExponential() method
- The Number toLocaleString() method
- The Number toFixed() method
- The Number isFinite() method
- JavaScript Reference: Number
- JavaScript Property Descriptors
- The Object assign() method
- The Object create() method
- The Object defineProperties() method
- The Object defineProperty() method
- The Object entries() method
- The Object freeze() method
- The Object getOwnPropertyDescriptor() method
- The Object getOwnPropertyDescriptors() method
- The Object getOwnPropertyNames() method
- The Object getOwnPropertySymbols() method
- The Object getPrototypeOf() method
- The Object is() method
- The Object isExtensible() method
- The Object isFrozen() method
- The Object isSealed() method
- The Object keys() method
- The Object preventExtensions() method
- The Object seal() method
- The Object setPrototypeOf() method
- The Object values() method
- The Object hasOwnProperty() method
- The Object isPrototypeOf() method
- The Object propertyIsEnumerable() method
- The Object toLocaleString() method
- The Object toString() method
- The Object valueOf() method
- JavaScript Reference: Object
- JavaScript Assignment Operator
- JavaScript Internationalization
- JavaScript typeof Operator
- JavaScript new Operator
- JavaScript Comparison Operators
- JavaScript Operators Precedence Rules
- JavaScript instanceof Operator
- JavaScript Statements
- JavaScript Scope
- JavaScript Type Conversions (casting)
- JavaScript Equality Operators
- The JavaScript if/else conditional
- The JavaScript Switch Conditional
- The JavaScript delete Operator
- JavaScript Function Parameters
- The JavaScript Spread Operator
- JavaScript Return Values
- JavaScript Logical Operators
- JavaScript Ternary Operator
- JavaScript Recursion
- JavaScript Object Properties
- JavaScript Error Objects
- The JavaScript Global Object
- The JavaScript filter() Function
- The JavaScript map() Function
- The JavaScript reduce() Function
- The JavaScript `in` operator
- JavaScript Operators
- How to get the value of a CSS property in JavaScript
- How to add an event listener to multiple elements in JavaScript
- JavaScript Private Class Fields
- How to sort an array by date value in JavaScript
- JavaScript Public Class Fields
- JavaScript Symbols
- How to use the JavaScript bcrypt library
- How to rename fields when using object destructuring
- How to check types in JavaScript without using TypeScript
- How to check if a JavaScript array contains a specific value
- What does the double negation operator !! do in JavaScript?
- Which equal operator should be used in JavaScript comparisons? == vs ===
- Is JavaScript still worth learning?
- How to return the result of an asynchronous function in JavaScript
- How to check if an object is empty in JavaScript
- How to break out of a for loop in JavaScript
- How to add item to an array at a specific index in JavaScript
- Why you should not modify a JavaScript object prototype
- What's the difference between using let and var in JavaScript?
- Links used to activate JavaScript functions
- How to join two strings in JavaScript
- How to join two arrays in JavaScript
- How to check if a JavaScript value is an array?
- How to get last element of an array in JavaScript?
- How to send urlencoded data using Axios
- How to get tomorrow's date using JavaScript
- How to get yesterday's date using JavaScript
- How to get the month name from a JavaScript date
- How to check if two dates are the same day in JavaScript
- How to check if a date refers to a day in the past in JavaScript
- JavaScript labeled statements
- How to wait for 2 or more promises to resolve in JavaScript
- How to get the days between 2 dates in JavaScript
- How to upload a file using Fetch
- How to format a date in JavaScript
- How to iterate over object properties in JavaScript
- How to calculate the number of days between 2 dates in JavaScript
- How to use top-level await in ES Modules
- JavaScript Dynamic Imports
- JavaScript Optional Chaining
- How to replace white space inside a string in JavaScript
- JavaScript Nullish Coalescing
- How to flatten an array in JavaScript
- This decade in JavaScript
- How to send the authorization header using Axios
- List of keywords and reserved words in JavaScript
- How to convert an Array to a String in JavaScript
- How to remove all the node_modules folders content
- How to remove duplicates from a JavaScript array
- Let vs Const in JavaScript
- The same POST API call in various JavaScript libraries
- How to get the first n items in an array in JS
- How to divide an array in multiple equal parts in JS
- How to slow down a loop in JavaScript
- How to load an image in an HTML canvas
- How to cut a string into words in JavaScript
- How to divide an array in half in JavaScript
- How to write text into to an HTML canvas
- How to remove the last character of a string in JavaScript
- How to remove the first character of a string in JavaScript
- How to fix the TypeError: Cannot assign to read only property 'exports' of object '#<Object>' error
- How to create an exit intent popup
- How to check if an element is a descendant of another
- How to force credentials to every Axios request
- How to solve the "is not a function" error in JavaScript
- Gatsby, how to change the favicon
- Loading an external JS file using Gatsby
- How to detect dark mode using JavaScript
- Parcel, how to fix the `regeneratorRuntime is not defined` error
- How to detect if an Adblocker is being used with JavaScript
- Object destructuring with types in TypeScript
- The Deno Handbook: a concise introduction to Deno 🦕
- How to get the last segment of a path or URL using JavaScript
- How to shuffle elements in a JavaScript array
- How to check if a key exists in a JavaScript object
- Event bubbling and event capturing
- event.stopPropagation vs event.preventDefault() vs. return false in DOM events
- Primitive types vs objects in JavaScript
- How can you tell what type a value is, in JavaScript?
- How to return multiple values from a function in JavaScript
- Arrow functions vs regular functions in JavaScript
- In which ways can we access the value of a property of an object?
- What is the difference between null and undefined in JavaScript?
- What's the difference between a method and a function?
- What are the ways we can break out of a loop in JavaScript?
- The JavaScript for..of loop
- What is object destructuring in JavaScript?
- What is hoisting in JavaScript?
- How to change commas into dots with JavaScript
- The importance of timing when working with the DOM
- How to reverse a JavaScript array
- How to check if a value is a number in JavaScript
- How to accept unlimited parameters in a JavaScript function
- JavaScript Proxy Objects
- Event delegation in the browser using vanilla JavaScript
- The JavaScript super keyword
- Introduction to XState
- Are values passed by reference or by value in JavaScript?
- Custom events in JavaScript
- Custom errors in JavaScript
- Namespaces in JavaScript
- A curious usage of commas in JavaScript
- Chaining method calls in JavaScript
- How to handle promise rejections
- How to swap two array elements in JavaScript
- How I fixed a "cb.apply is not a function" error while using Gitbook
- How to add an item at the beginning of an array in JavaScript
- Gatsby, fix the "cannot find module gatsby-cli/lib/reporter" error
- How to get the index of an item in a JavaScript array
- How to test for an empty object in JavaScript
- How to destructure an object to existing variables in JavaScript
- The Array JavaScript Data Structure
- The Stack JavaScript Data Structure
- JavaScript Data Structures: Queue
- JavaScript Data Structures: Set
- JavaScript Data Structures: Dictionaries
- JavaScript Data Structures: Linked lists
- JavaScript, how to export a function
- JavaScript, how to export multiple functions
- JavaScript, how to exit a function
- JavaScript, how to find a character in a string
- JavaScript, how to filter an array
- JavaScript, how to extend a class
- JavaScript, how to find duplicates in an array
- JavaScript, how to replace an item of an array
- JavaScript Algorithms: Linear Search
- JavaScript Algorithms: Binary Search
- JavaScript Algorithms: Selection Sort
- JavaScript Algorithms: Quicksort
- JavaScript Algorithms: Merge Sort
- JavaScript Algorithms: Bubble Sort