Ask coding questions

← Back to all posts
How do I use draw image in Javascript
woodyloody (7)

I have been wondering how to add images to a canvas and found the drw image function. I was wondering why it would not work when i have tried using it in my code and i was wondering if someone could help me.

https://repl.it/@woodyloody/Html-and-JS-Practice

Commentshotnewtop
JustARatherRidi (191)

Your code was right, you just forgot the <script> tag!

Here's a working repl

You'll notice I've added a couple more arguments, those are just to resize the image.


You might have noticed that it is a bit convoluted to work with the canvas API in plain javascript. You know, getting the canvas, then getting a reference to its context, making a separate <img> element, and all that just to draw an image.

So if you plan to do anything that involves a canvas, I highly recommend p5.js. It's super intuitive and it abstracts away everything wrong with the canvas API, and there's so much you can do with it. There's also the youtube channel called Coding Train. He's got really nice videos on p5.js, and it's frankly quite hard not to get inspired watching some of his videos.


I hope this helped!

heyitsmarcus (288)

@JustARatherRidi I love, love, love the Coding Train, and p5.js is a great library. I've been a patron of Dan for the past couple years.

JustARatherRidi (191)

@heyitsmarcus That's really nice, good on you!

heyitsmarcus (288)

Hey @woodyloody,

The reason you're not seeing the image is that you have to link the JavaScript file to your HTML page. You need to put a script tag in the bottom of your body with a src attribute to the script.js file like this:

<html>
<body>

<p>Image to use:</p>

<img id="scream" width="220" height="277"
src="s.jpeg" alt="The Scream">

<p>Canvas:</p>

<canvas id="myCanvas" width="240" height="297"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script src="script.js"></script>
</body>
</html>

And if you always leave the script at the bottom of the page, you don't need to use window.onload to start your code.

If this solves your problem, please consider upvoting and marking my answer as the accepted answer to close this question. But, I'll continue answering any questions you may have.