Search code examples
javascripthtmlhtml5-canvas

net::ERR_FILE_NOT_FOUND after creating an img element in JavaScript and trying to use it


I created an img element in JavaScript and gave it a DataURI as a source:

img = new document.createElement('img');
img.src = saveFrame();

The saveFrame function returns a DataURI (which is valid), and when i try console.log(img) the image element seems alright, but when i try running cctx.drawImage(img, x, y, cboard.width, cboard.height) it throws the error.

What I've tried:

  • using var : var img = document.createElement('img')
  • using new Image() : img = new Image()

I expected the Image to get drawn onto the canvas (that's called cboard, and has a context: cctx)

Actual results:

  • Firefox: gives no output in the console, and it doesn't work.
  • Chromium: the code doesn't work and throws: enter image description here

Other info:

OS: Manjaro Linux | Chromium version: 110.0.5481.177 | Firefox version: 110.0


Solution

  • fixed by using onload handler:

    const board = document.getElementById('board');
    const ctx = board.getContext('2d');
    
    const board2 = document.getElementById('board2');
    const ctx2 = board2.getContext('2d');
    
    function draw(){
      ctx.moveTo(40,40);
      ctx.lineTo(40,80);
      ctx.lineTo(80,0);
      ctx.stroke();
    }
    
    function transfer(){
      img = new Image();
      img.src = board.toDataURL('png'); //saveFrame()
    
      img.onload = ()=>{
        ctx2.drawImage(img, 0, 0);
      }
    }
    body{
      background: black;
    }
    
    canvas{
      background: white;
    }
    
    button{
      z-index: 3;
    }
    <canvas id="board"></canvas>
    
    <canvas id="board2"></canvas>
    
    <button onclick="draw()">draw image</button>
    <button onclick="transfer()">transfer image</button>

    using the getImageData() method is better, and doesn't require the onload handler:

    const board = document.getElementById('board');
    const ctx = board.getContext('2d');
    
    const board2 = document.getElementById('board2');
    const ctx2 = board2.getContext('2d');
    
    function draw(){
      ctx.moveTo(40,40);
      ctx.lineTo(40,80);
      ctx.lineTo(80,0);
      ctx.stroke();
    }
    
    function transfer(){
      img = ctx.getImageData(0,0,board.width,board.height); //saveData()
    
      ctx2.putImageData(img, 0, 0);
    }
    body{
      background: black;
    }
    
    canvas{
      background: white;
    }
    
    button{
      z-index: 3;
    }
    <canvas id="board"></canvas>
    
    <canvas id="board2"></canvas>
    
    <button onclick="draw()">draw image</button>
    <button onclick="transfer()">transfer image</button>