HTML5 Canvas Tutorial for Beginners [How to Draw Shapes with JavaScript]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Wow, very cool! It's always amazing what can be accomplished with code.

👍︎︎ 3 👤︎︎ u/setittowumb0 📅︎︎ Aug 14 2020 🗫︎ replies

Wow since when is Lord Tensai doing js tutorials

👍︎︎ 1 👤︎︎ u/edonmez01 📅︎︎ Aug 15 2020 🗫︎ replies

!remindme 8 hours

👍︎︎ 1 👤︎︎ u/curryoverlonzo 📅︎︎ Aug 15 2020 🗫︎ replies
Captions
have you recently started with javascript learned what the function variable and object is and now you're looking to build your first beginner-friendly project or have you been using html5 canvas for a while and want to learn a bit more about how it works under the hood then this video is for you in today's html5 canvas tutorial for beginners we will learn how to draw shapes with javascript and we will use the basic knowledge in a powerful way to draw randomized fibonacci flowers welcome to another addition to our shapes of nature creative series hi coders welcome to my creative coding series where we learn front-end web development techniques by building generative art projects with just plain vanilla javascript all the skills and techniques we learn here our fundamental javascript principles are completely transferable and can be used to build websites digital art applications and games in each episode we add a couple of new techniques to our front-end web developer coding toolkit getting you one step closer to your successful coding interview in short we make cool things while learning javascript in today's html5 canvas tutorial for beginners we will draw shapes with javascript and we will learn how to create so-called fibonacci flower algorithm also known as golden ratio or phylotaxis this is often seen in nature in for example pine cones seashells or sunflower seed arrangements there is a perfect youtube video that covers the basics of this principle and then it goes really deep into what's happening mathematically if you are interested and have 10 minutes to spare there is a link in the video description and if you want this principle to explain by dan schiffman in p5.js you can watch his coding train video and you can also watch all his videos while you're there he's the best simply said fibonacci numbers create a sequence where each number is the sum of the two precedent ones starting with zero and one the sequence goes like this zero plus one is one one plus one is two two plus one is three three plus two is five five plus three is eight and so on fibonacci sequence starts with 0 and 1 and it is a very common interview question where you will be asked to write an algorithm that returns numbers that create fibonacci sequence to draw so-called fibonacci flower we do not necessarily have to start with 0 and 1. we can choose any two numbers to start with if this is your first time here let me know in the comments and say hi my name is frank and i'm a self-taught front-end web developer i learned everything i know online in my free time mostly from youtube and udemy what is your story if you want to share leave a comment and let's have a chat about it this vanilla javascript coding tutorial will be focused on html5 canvas element and its fundamentals we will look into how it works under the hood and we will investigate where are all these methods that allow us to draw shapes coming from the first part of this video will be very beginner friendly and i will take you step by step through canvas setup and creating your first interactive canvas animation in the second part of this video we will add a small algorithm that allows us to draw randomized flower shapes and finally in the third part of this video we will put on our lab coats and do some coding experiments let's see where we can take this effect i will do my best to make this as beginner friendly as possible if you get any value from my tutorials click the like button please other than generative art i also do css animations and javascript game development so you can check out my playlist if you want let's start coding [Music] we will work with three files as usual in index.html we'll install css file create html5 canvas element with an id of canvas 1 and link our javascript file i called it script.js in style css i set canvas to position absolute i give it border 1 pixel solid black actually let's make the border 2 pixels and i will also give it blue background so we can see its size i want the canvas to cover the entire browser window so i set its top position to zero pixels left to zero pixels with hundred percent and height hundred percent you can't see it on my preview but because i have border around my canvas my page is showing scroll bars if i want to remove them i can set overflow to hidden on the body element canvas element is a special type of html tag that basically creates a drawing board where we can use javascript to create interactive circles rectangles lines and so much more we can use two different apis to draw on canvas api in this case means a set of built-in methods like fill rect to draw a rectangle filled with color or arc method to draw a circular path these methods are part of so-called canvas api which largely focuses on 2d graphics the other type is so called webgl api which also uses html canvas element to draw hardware accelerated 2d and 3d graphics so to use javascript to draw on html5 canvas element we have just created first i need to save a reference to that element in a variable i call that variable canvas and i point javascript to the correct html element by targeting its unique id i say const canvas equals to document.getelementbyid and i pass it id i gave it in index.html which is canvas1 as i said we have two different apis that allow us to draw on canvas canvas api and webgl api i will use canvas api which focuses on 2d to do that i create a new variable i call it for example ctx shortcut for context and i set it equal to canvas which is a variable from line 1 dot get context and as an argument i pass it 2d this tells javascript which one of these two apis i want to use for my project if i wanted to do 3d i would pass it webgl here instead there is also an optional second attribute where we can adjust settings like anti-aliasing alpha depth power of preference to set how much power we want to draw from our graphics card this is especially for webgl i will cover that in some other tutorial let's just keep this video as simple as possible and cover the basics of 2d so now i can call all built-in canvas api 2d methods from this ctx variable methods that allow us to draw line circle square and so much more i will show you what i mean in a minute i set canvas width to window in width and canvas height to window in a height to make sure the canvas covers the entire browser window all this code will run just once on the initial page load so if you want to change canvas size when you resize browser window this code from line 3 and 4 will have to go inside resize event listener so it runs every time resize even occurs in browser i will show you a bit later so now we are done with canvas setup and we are ready to draw i want to draw a circle first the way canvas api draws circles is using arc method which can also be used to create curved lines so called paths first we create programmatic path and then we can fill it with color or just outline it with stroke to draw a path on canvas first i have to call built-in beginpath method think of it as telling javascript you want to start drawing by putting pencil on the canvas then i call ctx arc which expects at least five attributes position on the horizontal x-axis position on the vertical y-axis circle radius which will determine its size start angle on circular path around the starting coordinates and end angle so i will set position x to 10 position y to 10 radius to 5 start angle will be 0 and end angle will be math.pi times 2 which is a value in radians that converts exactly to 360 degrees which is a full circle then i call closed path and ctx fill which will fill our pathway color if we don't declare any color it will be black by default i can change its coordinates by adjusting these two values and i can make it larger by changing its radius property to let's say 50. in style css i remove border and background on the canvas and back in script.js i set fill style to red i can also call stroke which will highlight the circle path with border by default this border will be 1 pixel wide and black color i can change this by setting line width to 5 let's push it down a bit and set stroke style to blue notice how i call all these built-in methods like beginpath arc and close path from ctx variable we declared online 2. that is because on line 2 i set ctx to be equal to whatever canvas.getcontext2d method returns you might have heard that almost everything in javascript is an object that certainly applies here and getcontext2d returns a built-in object called canvasrenderingcontext2d on line 2 i am assigning that special object to our ctx variable and if you console.log ctx you can see the object itself its properties like fill style and font and all of its built-in methods that's how canvas 2d api works we are just pulling these pre-built methods from this object and calling them the draw on canvas back to our project so far we have drawn a circle we can also draw a rectangle which is a bit simpler all we need is a built in fill rect method and we pass it for attributes x and y position and width and height like this we can change its position and size by changing values here i will delete the rectangle now we have our circle how do we make it move i create a custom function called animate its job will be to create our animation loop which will just basically redraw canvas over and over creating an illusion of movement so first there will be some code to draw each frame and then i passed it built-in request animation frame function all this function does is it calls whatever function we pass to it as an argument if i pass it animate the name of its parent function our animate function will just call itself over and over create an animation loop through a programming principle called recursion i take all the code we wrote to draw our circle and i put it inside the animation loop now we have a blank canvas because on line 8 i declare function i called animate but it doesn't run its code to run it i need to call that function saying animate and brackets like this when i do that javascript jumps from line 20 back to line 8. it runs all the drawing code to create our circle between lines 10 and 17 and on the line 18 we have request animation frame that makes javascript jump back to line 8 and call animate again this will be happening over and over so we have our animation loop everything is being redrawn now even though it looks static to prove to you that animation loop works i go to line 14 and inside arc method i replace radius of 50 with a variable i call it size and on line 6 i declare it and set it equal to 0. notice i'm using let variable instead of const that is because size is 0 now but it will change for every frame of animation i want to make the circle grow so on line 10 inside animation loop i say every time this loop is run increase size variable from the line 6 by 1 and since this variable is part of our arc method on line 16 it will affect the size of the circle that's being drawn for every frame like this click the like button please if you're getting any value from my tutorials subscribe and hit the bell icon if you want to be notified when i release a new creative coding video i can change value on line 10 to set how fast our circle is growing i can also make it move i replace x coordinate on line 16 and instead of drawing our circle at a starting position 100 pixels from the left side i place a variable here i call it position x for example and on line 7 i declare position x as a global led variable and i set it to 0 at first inside animation loop i say for each frame increase position x variable by 0.1 maybe a bit more 0.5 and we have a growing circle that moves to the right you can see it's leaving a path behind that is because we still see old frames if we only want to see the current frame i can go inside animation loop and call ctx clear rect method this will clear specified area of cadvas from any old paint i want to clear the entire canvas so i pass it 0 0 canvas width canvas height and now we can only see the current frame because old paint is being deleted between every animation frame i can change values on size and position x variables to make the circle grow and move slower or faster depending what value i assign it to we can keep all this code inside animation loop like this but it started to look a bit messy i would prefer to have our drawing code in a separate function for clarity i go up to line 9 and i create a custom function i call for example draw flower then i cut all the drawing code from inside animate and i paste it inside the custom draw flower function i just created now our drawing code is clearly separated and i can just call draw flower from inside animation loop like this we still get the same result but our code is cleaner now i can also replace vertical y coordinate with a custom variable so on line 14 i replace 300 with a variable i call for example position y and on line 8 i declare that variable and set it equal to 0. then on line 27 inside animate i say every time animation loop runs increase position y variable by 0.5 and this is what happens we create a simple vector for our circle it means we give it direction and speed we can change these values to make it move in a different direction like this the base principle with algorithmic flower is circle movement how do i make our circle shape to move around canvas in a circular path don't get scared now when i say word trigonometry it's not that difficult i promise we have covered basic canvas principles now we are venturing into intermediate territory but i will still do my best to keep you with me and i will explain everything i am doing i create a variable i call angle and i set it equal to zero inside animation loop i set angle to increase by 0.1 for every frame of animation on line 26 i comment out code that increases size and on line 6 i set size to be a static number let's say 10 or 20. actually let's remove the variable completely and i will hard code radius size 20 inside arc method on line 15. on line 25 we have a variable that determines horizontal position of our particle i will multiply it by math dot sign built in javascript method and i pass it angle the variable we declared on line eight and which we are increasing by 0.1 for every frame of animation on line 27. all that math.sine does is it returns a number between -1 and plus 1. this number represents the sine of the angle we gave it in radians very simply said if you call math of sine and pass it a number that slowly increases in this case we pass it our angle variable it will fluctuate between -1 and plus 1 so the resulting movement will look like this let's push the circle away from the left edge by increasing position x variable on line 6. see how its only horizontal movement is wobble to left and right if i increase this number on line 25 it will increase the range of the movement by default math.sine cycles between -1 and plus 1. if we multiply it times five the range will be minus five to plus five i can also do the same for position y i say one times math.sine and i pass it angle variable as an argument again all mathematics sign is doing is translating ever increasing number inside angle variable to a range between minus 1 and plus 1. if we use sine for both x and y positions we will get a simple back and forth paths like this let's move it down by increasing position y variable on line 7 to 100. if i want a circular movement i need to change sine to cosine sine and cosine work together in sync to map a path along a circular area cosine is the same as sine it's just returning the opposite value from the range between minus 1 and plus 1. don't worry if you can't understand this 100 yet all we need to know for this effect is how to use these methods it will make more sense if you use it more than once so if i change 1 to 5 on line 26 our ellipse path will change into a perfect circle like this on lines 25 and 26 i can change this value to make the circular path smaller or larger i can also adjust value on line 27. on lines 6 and 7 i can set these values to be in the middle of the canvas but as you can see it is not exactly centered we will fix that in a minute right now we are clearing canvas after every step of animation what happens if i stop clearing the canvas so we can see the old paint as well i comment out line 23 and now i can see all previous positions for our particle this will be crucial to draw algorithmic flowers some of you might already see how we will go about drawing the flowers basically all i need to do now is to slowly increase the size of circular path as the particle spins around before i do that i will restructure and clean the code up a bit inside draw flower i create three variables angle x and y and i set them to 0. these variables will completely replace position x position y and angle variables from lines 6 7 and 8. actually let's not make it confusing i will keep the same naming so on line 12 i will call the variable position x and on the line 13 i will call the variable position y now i can delete variables with the same name from the line 6 and 7 and i can also delete angle variable on the line 6 because it will be replaced by angle variable inside draw flower function i will also need one more variable i will call it radius this will determine size of circular path our particle is taken i will show you in a minute i go down to animate function and i delete everything between lines 25 and 28. on line 6 i create a variable i call number this will simply increase by one every step of animation and each time it increases one particle or petal on our flower will be drawn i also create a variable i call scale and i set it to 10 for example this will play a role in making our radius grow so our flower grows from the center outwards on the line 10 i say angle is equal to number variable from line 6 times 1. this number will determine final shape of the flower i will show you in the experiments part of this video how it works exactly radius on line 13 is equal to scale variable from line 7 times math dot square root and i pass it number from line 6 also i will explain in a second all i want to happen here is for the radius to slowly increase to draw layers of petals in our flower but i wanted to increase very slowly so that's why i use math dot square root i cut position x and position y variables and i paste them here they need to come after the radius because we need radius to already be calculated so we can calculate current x and y position for the particle position x will be radius times math.sine and i pass it angle like we did before and position y will be radius times math.cosine and i pass it angle as well i want position x and position y to map values along a growing circle path to make sure the path is growing and our particle is not just being drawn on top of itself over and over i go to line 24 and i say number plus plus which will make it increase by 1 for every frame of animation our number variable was declared on line 6 and as it increases it changes values of angle variable on line 10 and radius variable on line 11 and then both angle and radius variables are used on lines 12 and 13 to calculate current position x and position y of coordinate for our particle if you look at this code closely all that is happening on line 10 is i am increasing angle variable because it's equal to number variable that is increasing on line 24 and then i am passing that ever increasing angle variable to sine and cosine on lines 12 and 13 same like we did in our first simple example before sine and cosine simply just transfer any angle we pass to it as an attribute into a range between minus one and plus one and we use that behavior to map position along a circular path and if we multiply this number by anything let's say five the range will increase from minus one to plus one to minus five to plus five so the circle will grow in this case on lines twelve and thirteen i am multiplying sine and cosine by radius variable from line eleven radius variable again is simply just a very small slowly increasing number that makes sure the radius of circular path our particles taken is getting larger and larger to draw the final flower shape the flower is being drawn from the top right corner so i can just move it to the middle of canvas horizontally here on line 12 by saying plus canvas width divided by 2 and vertically on line 13 by saying plus canvas height divided by 2. i can change color of the fill here on line 15 and i can change stroke color on line 16. look at what we can do with just 37 lines of javascript time for some experiments it can look much better than this click the like please if you're getting any value for my tutorials but before we do that let's just quickly look at the code first we did our initial canvas setup on lines one to four then we created some global variables to use as settings for our algorithm on lines six and seven this effect is drawn by a single spinning particle inside the draw flower function we first calculate position for this particle for this particular animation frame on lines 10 to 13. then we use canvas api built-in drawing methods to draw a shape we want if you want to replace circle with something else you can replace it with a square rectangle star hexagon or image you can do that just by replacing the code here for each frame we also increase our number variable on line 24 this will cause the particle that draws our effect to move around and lastly we create animate function which has only one job and that is just to run draw flower function over and over and make the single particle spin around in circles to create our final flower shape we could replace this with javascript set interval but request animation frame is better because it will adjust to your screen refresh rate always try to use request animation frame like this over set interval for your generative art projects if you can it's a good practice for performance especially to prove to you that this is just one particle spinning around that draws our effect i can just go down here to line 29 and i can uncomment clear rectangle which will remove old paint between every animation frame now you should be able to see what's happening with this effect single spinning particle that draws everything i comment it out again and let's do some experiments let's make it look good look what happens when i change this value on line 10. every time i change this value it draws completely different flower shape i can spend hours just playing with this by tweaking values here because you can also put very small numbers here look what happens if i go to line 19 and i replace size of our drawing particle with number variable remember that number variable is declared on line 6 and it increases by 1 for every frame of animation so the particle that draws our flower effect will be growing i don't want it to be growing endlessly let's introduce some limits on line 31 inside animate i say if number is more than 300 return return in javascript is a special keyword and it will make function to stop on that line so when number variable we are increasing on line 24 grows to 300 animate function will return on line 31 and request animation frame online 32 will not run again to serve the next animation frame when the number reaches 300 animation will stop i can change limits to 100 i change fill style have you heard about global composite operation property on canvas element i used it for a couple of effects uh here on the channel before this property of canvas 2d api sets what type of compositing we want when drawing new shapes on canvas what it means in simple language is by using this property we decide how individual shapes on canvas stack interact and overlap similar to layers in photoshop there are around 26 different settings if i set it to destination over new shapes are drawn behind the older ones drawing goes kind of backwards and it's really good for this particular flower shape we are trying to achieve in this video let's set line width to 4 and fill style to gray i can change shape of flower by changing number here on line 11. what is happening here is just simply i am telling the particle that spins around circular area to draw our flower how far it should skip between every step different interval between skips along a circular path will create different shapes if i use a very small number here you can see it doesn't even skip far enough between stages where individual circles are drawn and we just get the shape like this eventually it will give us kind of a snail shell which i really like adjusting if statement on line 32 will allow us to draw larger flowers i can play with this and tweak all these values to see what shape it gives us i can also show you how to give it rainbow colors on the line 16 i set fill style to hsl color declaration this takes three attributes view saturation and lightness if i set hue to one we will get right color the first attribute can be anything between number one and 360 and each number is 1 degree on hsl color wheel so changing this number will cycle through the entire color spectrum i made a special video about colors on canvas if you want to learn more about hsl color declaration and canvas gradients you can watch it later when hsl reaches 360 it just starts from the beginning and the cycle starts from the red color again i can create a global variable i call hue and initially i set it to 0 on line six now down here on line 27 inside animation loop i say for every frame increase hue by one view plus plus on line 17 in fill style inside hsl color declaration i just replace value for you with this variable to make the statement dynamic now if i run the code we are cycling through all the colors as the flower grows i try to give it black stroke if i wanted to cycle through color slower i can say only increase hue by 0.5 for each frame of animation here on line 27 by saying you plus equals 0.5 also maybe i don't always want to start from 0 which is red color maybe i want to start from a random color whenever new flower is created to do that i simply set the initial u on line 6 to a random number between 0 and 360. and now each time new flower is drawn we start from a different color i will make a special video on global composite operation because there is so much more we can do with it click the like button please if you're getting any value from my tutorials subscribe and hit the bell icon if you want to be notified when i release a new creative coding video if you want more generative art vanilla javascript game development or css animation check out my playlists in the video description down below thank you so much for watching and well done if you manage to follow along all this way through see you next time [Music]
Info
Channel: Franks laboratory
Views: 19,896
Rating: undefined out of 5
Keywords: franks laboratory, frankslaboratory, HTML5 Canvas Tutorial for Beginners, How to Draw Shapes with JavaScript, HTML5 canvas tutorial, HTML5 canvas for beginners, HTML5 canvas, HTML5 canvas basics, fibonacci sequence, canvas, javascript, tutorial, html, animation, html5, html5 tutorial, canvas element, software tutorial, beginners, web, development, html5 tutorial for beginners, learn, animate, shape, script, drawing, canvas tag, html canvas, vanilla javascript
Id: ymmtEgp0Tuc
Channel Id: undefined
Length: 32min 22sec (1942 seconds)
Published: Fri Aug 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.