Draw an image to the canvas
JavaScriptTranscript
English (Auto-generated)
hi everyone in this code cast we will discover drawing images to the canvas and additionally we will also use the filter property with different values to apply effects such as blurring and gray scaling the image. So in my html, I've already set up the canvas element and In my search here says I have set my width of the canvas to be 70% a height auto and it has this border around it. Just like we've been using in the previous court cast and in my javascript I have a reference to the canvas element and a two D context object. So first let's start drawing the image to the canvas with let I M. G. It's equal to new image. No, and let me explain what we're doing here. So we've used the built in image constructor to instant she ate a new image and now the next part for us is to actually set the source of the image. So I'm going to grab an image from google and I will use a picture of a dog so this dog and copy image address and then come back to the code editor. And now let's set the source attribute of the image. So I M G dot SRC is equal to and then within a single or double quotes the source of the image that you just copy, paste it. So the link and you could have used the set attribute method as well. This is just a bit faster. Now next let's add an event listener which is attached to the image element and we'll listen out for a load event and execute a callback function in response to the load event. So let's just structure this first. So I M G dot add event listener. So I'm using the add event listener method and this is going to listen out for a load event. So when the image loads, we want to execute a callback function in response and there you go. Now the function will draw the image onto the canvas using the draw image method. And the draw image method takes four arguments. The starting X value, the starting Y value. So let's structure this so context. So the t uh sorry the two D context is going to take the draw image method right? So we're going to use the drawing image method on the context to the context and we will pass in the image that we want. It should be drawn to the canvas, we pass in starting X value at zero, starting wide value at zero. So we want to start drawing the image in the upper left corner of the canvas. And then canvas dot with comma canvas got a hike and the image is going to span the width and height of the canvas now go ahead and let's just control s and there you go. So we've drawn an image to the canvas now this is not very exciting because you could have just put the image in let's say a dev and used an image tag. But what is exciting about putting an image or drawing an image to the canvas is all the other cool stuff that you can do later on with it. So you could, you know, draw triangles on top of these images squares like we did in the previous code cast, and we can also apply filters to this image like we will in the next podcast.