Khaled
Khaled

Reputation: 15

How to draw an image in a canvas

So I was trying to draw animgin a canvas I tried everything but in the console it says img is not a property or something like that I don't remember so can anyone help? Here's the js

function setupcanvas() {
  var canvas = document.querySelector('canvas')
  var c = canvas.getContext("2d")
  c.beginPath();
  var img = new image()
  img.src = "flappy_bird_bird.png"
  img.onload = function(){
    c.drawImage(img, 100, 100)
  }
}

Edit Thx to mhkanfer "sorry if the name is wrong" I fixed it

Upvotes: 0

Views: 470

Answers (1)

Ryan Grube
Ryan Grube

Reputation: 185

You were mostly right, though their are a couple of things:

  1. Make sure Image() is capitalized
  2. Make sure your image src file actually exists in that directory
  3. And make sure your canvas has a width and height, if you haven't specified that anywhere, you canvas wont be shown

If you were to revise this, it would look something like:

function setupcanvas() {

  var canvas = document.querySelector('canvas')
  var c = canvas.getContext("2d")

  canvas.width = canvas.height = 200;

  var img = new Image()
  img.src = "example.png"

  img.onload = function(){
    c.drawImage(img, 0, 0)
  }

}

Upvotes: 1

Related Questions