-1

Im trying to set up a background image in my html canvas by creating a function that clears the canvas and draws the background image to fill the canvas. I've been trying to figure out where I went wrong and why no images are appearing on preview. (I've already double checked my links for spelling errors)

`<html>
<head>
    <title>Apple Dropper</title>
    <meta charset = "utf-8">
    <script src ="proa1.js">
        // set src of images in variables
     var canvas = document.getElementById("myCanvas");
     ctx = canvas.getContext("2d");

 canvas.width = 600;
 canvas.height = 400;


 let bg = new Image();
 bg.src = "projectimages/gifani.gif";

 let pic = new Image(0,350);
 pic.src = "projectimages/bucket.png";

 let fish = new Image(300,0);
 pic.src = "projectimages/fish.png";

 // Make sure the image is loaded first otherwise nothing will draw.

   bg.onload = function(){
      ctx.drawImage(bg,0,0);
   }
    </script>
</head>

<body>

    <h1>CPSC 1045 Apple Dropper Project</h1><br>
    <h2>Alleluia Anteros</h2>

    <!--- canvas --->
          <canvas id="myCanvas" width="600" height="400" style="border:1px solid #000000;" >
    </canvas>
    <br> 
    <!--- control panel --->

</body>
</html>`
idkbro
  • 1
  • 1
    You're doing this `var canvas = document.getElementById("myCanvas");` before `myCanvas` exists. Move your script to the end of the body. – JDunken Mar 21 '20 at 00:54

1 Answers1

0

If you want a regular background image it would be much easier to do so using CSS. You would select the body tag and use the background-img property with the value of URL and put the URL of the image in the parenthesis. To make to cover the page you would have to use the property of background-size with the value of cover.

body{
     background-img:url(bckgrndimg.png);
     background-size:cover;
}