title: How to fix "TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D'"?
body: <p>I am a beginner JavaScript programmer and I am following a book called "Create with &lt; code >" and I am having trouble with the code. I have been following along with the book but when I have tried running it, I get this error:</p>
  
  <blockquote>
    <p>Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)</p>
  </blockquote>
  
  <p>I have been typing the code into a plain-text editor and viewing it on Chrome. How do I fix this error?</p>
  
  <p>If you run the snippet you should be able to see the error.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//CONSTANTS
  var CANVAS_WIDTH = 800;
  var CANVAS_HEIGHT = 600;
  
  var GROUND_Y = 540;
  
  //SETUP
  var canvas = document.createElement('canvas');
  var c = canvas.getContext('2d');
  canvas.width = CANVAS_WIDTH;
  canvas.height = CANVAS_HEIGHT;
  document.body.appendChild(canvas);
  
  var cameraX = 0;
  var bushData = generateBushes();
  
  var bush1Image = new Image();
  bush1Image.src = 'bush1.png';
  
  var bush2Image = new Image();
  bush2Image.src = 'bush2.png';
  
  window.addEventListener('load', start);
  
  function start() {
      window.requestAnimationFrame(mainLoop);
  }
  
  function generateBushes() {
      var generatedBushData = [];
      var bushX = 0;
      while (bushX &lt; (2 * CANVAS_WIDTH)) {
          var bushImage;
          if (Math.random() &gt;= 0.5) {
              bushImage = bush1Image;
          } else {
              bushImage = bush2Image
          }
          generatedBushData.push({
              x: bushX,
              y: 80 + Math.random() * 20,
              image: bushImage
          });
          bushX += 150 + Math.random() * 200;
      }
      return generatedBushData;
  }
  
  //MAIN LOOP
  function mainLoop() {
      update();
      draw();
      window.requestAnimationFrame(mainLoop);
  
  }
  
  //UPDATING
  function update() {
  
      //Update bushes.
      for (var i = 0; i &lt; bushData.length; i++) {
          if ((bushData[i].x - cameraX) &lt; -CANVAS_WIDTH) {
              bushData[i].x += (2 * CANVAS_WIDTH) + 150;
          }
      }
  }
  
  //DRAWING
  function draw() {
  
      //Draw the bushes
      for (var i = 0; i &lt; bushData.length; i++) {
          c.drawImage(
              bushData[i].image,
              bushData[i].x,
              GROUND_Y - bushData[i].y);
      }
  
  }</code></pre>
  </div>
  </div>
  </p>