Learn to Code via Tutorials on Repl.it!

← Back to all posts
An introduction to the JS Canvas
liltaco

(This post was originally made for dev.to. Click here to see the original post)

## Prerequisites:

This tutorial is made for beginners. It's enough if you know that let is the block scope var and you know how to use const.

Who this is for

Most of your webapps so far probably consisted of getting inputs from elements, listening to button presses, modifying texts, and maybe even making new elements. This quick tutorial will teach you how to make graphics in JS starting with basic shapes, but the possibilities are endless!

The <canvas> element

The canvas element (from now on just called canvas) is the only element that can be drawn on. Before you draw on a canvas, it's completely transparent. The default size for a canvas is 300 by 150 pixels. This size can be changed with the width and height attributes.

Note: you can scale a canvas with CSS, but if the aspect ratio (ratio between width and height) is different, the image will stretch.

Note: As of the time of writing, 98.9% of browsers support canvas, so you shouldn't worry about compatibility because that's as common as CSS3 Box-sizing.

Setting everything up

To draw on a canvas, first get a reference to that canvas in the JS. The simplest and most common way to do so is using document.getElementById('id') which returns the element that has that specific id attribute.

index.html

Note: <canvas> tags must be closed.

style.css

script.js

You can fork this super minimalist starter on Repl.it if you want to save the hassle of copying and pasting this yourself. All following snippets only apply to the JS; the HTML and CSS will stay the same.

The rendering context

The canvas element is just an element. In order to draw on it, you need to get a rendering context. Rendering contexts are the ways you can draw on a canvas. Currently, these are CanvasRenderingContext2D and WebGLRenderingContext. 2D is the simplest to work with; it gives you functions for all kinds of shapes, texts and images. The main drawback of the 2D rendering context is that it runs on the CPU and not on the GPU, so it's much slower than WebGL. WebGL is a port of OpenGL ES 2.0 (a low-level graphics library) to the web that allows advanced graphics on the GPU. However, it's very complicated to use without libraries. This tutorial will only use the 2D rendering context.

To get the 2D rendering context, just type:

Drawing

Now that you have your rendering context, you can draw your very first rectangle:

ctx.fillRect accepts 4 parameters: x, y, width, height. The line ctx.fillRect(0, 0, 50, 100) will fill a rectangle with a width of 50 and a height of 100 with its top-left corner at x = 0 and y = 10.

The position x: 0, y: 0 is at the top-left corner, so a higher X value goes to the right and a higher Y value goes downwards.

Note: Everything you draw on a canvas will stick around until you either draw something on top of it or change the width and height attributes.

Colors

Colors in the 2D rendering context can be any CSS color, so you can write them hexadecimal, rgb(1, 2, 3), hsl(120, 100%, 50%), rgba, hsla, and conveniently you can use a color keyword.

Now, let's apply color to the rectangle.

There's ctx.fillStyle which is the color for filled shapes and ctx.strokeStyle for the color of the outlined shapes. Once you set the color, everything you draw will be drawn in that color until you change it.

Creating abstract art has never been easier!

In addition to fillRect and strokeRect, there's also clearRect. clearRect also gets x, y, width, height parameters, but clearRect will make everything inside of the rectangle transparent. If you want to clear the whole canvas, you can also do canvas.width = canvas.width or canvas.height = canvas.height because setting the canvas size will clear it too.

Advanced shapes

A path is a list of lines, which can be straight or curved. Once you have created a path, you call ctx.fill() or ctx.stroke() or even both to draw the path on the canvas.

Essential functions:

  • ctx.beginPath() resets the path, always run this before drawing something so it won't get mixed up with what you just drew.
  • ctx.moveTo(x, y) 'raises' the path pen and moves it to a position.
  • ctx.lineTo(x, y) will move the path pen to the given point in a straight line.
  • ctx.closePath() moves the path pen from the last point to the first point in a straight line.

If you want to draw curved lines or do something more advanced like path clipping, you can see the complete list of path methods from MDN.

Now, let's draw our first triangle!


It's coming together!

Common Shapes

Circle

There is no ctx.circle function, but there are 2 main ways to draw circles in the canvas.

  1. ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle) - as of writing this, it isn't supported on the Android webview which is an issue. That's why I usually use:
  2. ctx.arc(x, y, radius, 0, Math.PI * 2) - the 0 and the Math.PI * 2 are the startAngle and endAngle.

Here are some circles you can play around with:

https://repl.it/@liltaco/Canvas-Tutorial-Circles

Rounded Rectangles

There is no ctx.roundedRect() function, but you can use this modified snippet from MDN:

Just add this to the beginning of your code and every 2D rendering context will have the ctx.roundedRect method. (Object.prototype is basically a way to give every instance a new method).

Transformations

Sometimes, you may want to scale, move, or rotate everything you draw on the canvas.

  • ctx.save() pushes the current transformation state
  • ctx.restore() pops the previous transformation state
  • ctx.translate(x, y) moves the canvas origin x units to the right and y units down. Everything you draw will be moved that much.
  • ctx.scale(x, y) multiplies every unit by x and y; if it's less than 1 it scales everything down and if it's more than 1 it scales everything up.
  • ctx.rotate(angle) rotates everything you draw from now on by angle radians.

Transformation order matters!

If you do ctx.scale(2, 2) and then ctx.translate(10, 10), then everything will be translated 20 units by the original scale, but if you do ctx.translate(10, 10) and then ctx.scale(2, 2) everything will be translated 10 units by the original scale. The same applies for rotation too.

Transformations stack!

If you run ctx.scale(1.1, 1.1) then ctx.scale(1.1, 1.1) again will scale everything up by 21%. Each transformation will stack up on the previous transformation state the same as it would on an empty transformation state.

Try my Transformation Playground to learn by doing.

Final Notes

You generally can't put elements inside of a canvas since they aren't shown, but if a user has an ancient browser like Internet Explorer 8 from 2009, any elements inside the canvas will be visible. Therefore you can place some content describing what should be on the canvas in there or just say "Your browser doesn't support canvas" as fallback.

If you want to draw on top of another element, just place the canvas on top of it with CSS, then draw on the canvas (remember that a canvas is transparent by default).

Another useful tip is that if you want to draw in layers, i.e. not erase the background when erasing an overlay (useful for games where backgrounds are mostly static but need to be drawn), you can place a canvas on top of another canvas with CSS.

That's it for this tutorial!

Here are some pointers that you should read through:

Next up: Mouse and keyboard input for your interactive webapps

Voters
programmeruser
oniabc123
pera9522
olivierooms
Yasir4733
Vandesm14
Highwayman
lucasernesto
HackermonDev
mkhoi
Comments
hotnewtop
HackermonDev

I love this!

JacobRogers

Thank you!

amelietayloruk

Thank you for this great post. Are you looking for graduation assignment help in the UK? If yes, then contact UK Best Tutor, and you can get the top assignment's support at a low price.
https://www.ukbesttutor.co.uk/graduation-assignment-help

elenaalbie

Thanks for sharing a very informative post about programming students. We are offering programming assignment solutions at a very minimum amount. Here you can get all-time programming assignment help.
Get Solutions Here: https://www.assignmentclassmates.com/programming-assignment-help

MasonWilliam

Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post. 课程作业代写

RichardJoseph3

[url=https://www.phpbb.com/]Visit phpBB/url
<a href="https://www.w3schools.com/" target="_blank">Visit W3Schools!</a>

smithwick11

Do you also want Assignment help Malaysia? We lend expert writers for assisting you with the projects. Our qualified writers will assist you with everything. You will get 100% original content within the deadline. Hire our assignment helper online and finish your project works. https://www.greatassignmenthelp.com/my/

MasonWilliam

Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming. rosmarinic acid Extract wholesale

adamsmith49
TomasSamanter

Thanks to the author's comprehensive description, I learnt everything I needed to know about my topic after reading this post. I published a review that you may read on the domyhomework123 reviews. Thank you so much for your time and attention.

lineAde

Another distinguishing element of the world of solitaire is the option to discard moves if you get stuck or want to rearrange your tiles. Opportunities like these can be overlooked with more challenging games and regular players.

Cleo-RR

Junk removal is a service that allows you to have any type of waste removed from your house or company on demand. We transport heavy goods such as furniture and appliances, perform full house cleanouts, provide minor demolition in a number of areas, and collect all types of waste and building debris from real estate cleanouts.
https://brandenjunkservices.com/

RosalynK

whenever reading your Blog or especially this topic this is so conscious and very impressive to impose word. This is readable content. I would like to request please keep updating like a BLOG or service provider content. if you want read our Blog about Financial services you can visit this website https://vantagefinancialusa.com/

samtim21

I am passionate about learning different kinds of arts. This is my hobby apart from the job I am doing. I always wanted to learn new things and one day, dance has stimulated me. Let me aware you of the incident.
https://projectservicellc.com/

Amansa21

Oh!! It’s a piece of bad news. Why they are doing this. I thought that Madison Avenue always takes care of their clients. But this post says that they are ripping off its clients. google chrome won’t open That was not a good thing. We have to complain about it.https://classic-brow.com/

AlbertMarsh

Dissertationmasters can write a variety of written works for you. No matter what you need - tests, essays, reports, term papers or memo - our writing service can do it quickly and accurately.
https://dissertationmasters.com/memo-writing-service.html

KateeeJohnson

Reading your post I understood as informative and useful for me is it. As I am working on research sinopsis https://quality-writings.com/what-is-research-project-synopsis-writing for my project about IT technologies but I cannot choose the object of my paper. And this post helped me. I will write about canvas elements.

NextLevel3
NextLevel3

Very nice blog and articles. I am realy very happy to visit your blog. Now I am found which I actually want.
https://bynext.com/2019/07/21/free-domain-valuation-domain-appraisal-services/

NextLevel3
NextLevel3

Im positive to all of the commenters right here! Its constantly nice when you can not only be informed, but also entertained! I am certain you had enjoyable writing this write-up.
https://bynext.com/2020/06/12/livechat-30-day-free-trial-livechat-review-2020

NextLevel3

Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming
https://bynext.com/2020/12/13/landingcube-review-best-amazon-landing-page-builder/

NextLevel3
NextLevel3

I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe the reality.
https://bynext.com/2020/05/17/squarespace-review/

NextLevel3

I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe the reality.
https://bynext.com/2016/08/21/semrush-review-how-to-beat-competitors-in-search-2017/

NextLevel3

I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post.
https://bynext.com/2021/03/10/samcart-review/

NextLevel3

Very nice blog and articles. I am realy very happy to visit your blog. Now I am found which I actually want.
https://bynext.com/2020/07/12/anstrex-review-2020-best-push-ads-spy-tool-native-ad-network/

BillLawry
lukewhelanperth

PerthIsOk is a travel guide blog website and covers all famous tourist places, things to do, places to drink, places to eat, places where to go and best places to see in Perth , Western Australia.

http://perthisok.com/

devidstewart

If you are looking for an online assignment writing service for hire, you’re at the right place. Myassignmenthelperonline.com has a big team of rich academic experienced professional writers who undergo various tests before they start working for us. We have writers in every subject and hold several degrees.

Link: https://myassignmenthelperonline.com/assignment-writing-service.html