Search code examples
javascripthtmlcanvashtml5-canvas

Image not loading in canvas js


I'm making a webpage with a canvas with an image inside, but the image never shows, and I don't find the problem in the code.

var lienzo = document.getElementById("canvas1");
var papel = lienzo.getContext("2d");
var oveja = new Image();
oveja.src ="oveja.jpg"
oveja.addEventListener("load", dibujar());

function dibujar() {
  papel.drawImage(oveja, 0, 0);
}
body {
  font-family: sans-serif;
  background-color: rgb(240, 240, 150);
}

canvas {
  background-color: red;
  position: relative;
  top: 100px;
  left: 100px;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="styles.css" />
  </head>

  <body>
    <h1>
      Mi reto en Canvas
    </h1>
    <canvas id="canvas1" height="700px" width="700px"></canvas>
    <script src="script.js"></script>
  </body>
</html>

This is the expected result: 1

But it only draws the red square without the image, it doesn't show any error in the console.

What is wrong in the code?


Solution

  • You just need to change dibujar() to dibujar. This way you're passing the function itself not the function's return value as an argument.

    var lienzo = document.getElementById("canvas1");
    var papel = lienzo.getContext("2d");
    var oveja = new Image();
    oveja.src = "https://i.sstatic.net/5y9mz.png" // Here I changed the image so that the demo works
    oveja.addEventListener("load", dibujar);
    
    function dibujar() {
      papel.drawImage(oveja, 0, 0);
    }
    body {
      font-family: sans-serif;
      background-color: rgb(240, 240, 150);
    }
    
    canvas {
      background-color: red;
      position: relative;
      top: 100px;
      left: 100px;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>Parcel Sandbox</title>
        <meta charset="UTF-8" />
        <link rel="stylesheet" href="styles.css" />
      </head>
    
      <body>
        <h1>
          Mi reto en Canvas
        </h1>
        <canvas id="canvas1" height="700px" width="700px"></canvas>
        <script src="script.js"></script>
      </body>
    </html>