An introduction to the JS Canvas
(This post was originally made for dev.to. Click here to see the original post)
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
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
Note: you can scale a canvas with CSS, but if the aspect ratio (ratio between width and height) is different, the image will stretch.
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
Note: <canvas> tags must be closed.
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
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:
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.
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
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%),
hsla, and conveniently you can use a color keyword.
Now, let's apply color to the rectangle.
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
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.
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!
There is no
ctx.circle function, but there are 2 main ways to draw circles in the canvas.
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:
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:
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).
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
xunits to the right and
yunits down. Everything you draw will be moved that much.
ctx.scale(x, y)multiplies every unit by
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
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.
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.
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
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.
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
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/
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.
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/
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.
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.
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.
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.
Very nice blog and articles. I am realy very happy to visit your blog. Now I am found which I actually want.
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.