How to assign an image that is on the screen as a canvas background

Asked

Viewed 83 times

1

I have a canvas and I need to put how background an image that is already on the screen.

Example:

<div id="imagens">
    <canvas id="canvas" width="600" height="700" style="border: 1px solid black"></canvas>
</div>

I have this fraction of code that puts an image of the site as backgroud document.getElementById("canvas").style.backgroundImage = "url('http://www.xxxxxx.yyy.br/1005.jpg')";

But I need to get the picture that’s on id="imgpreview" and places it as the background of CANVAS.

1 answer

1


Just take the value stored in the attribute src of the image.
Example:

var canvas = document.querySelector("#canvas");
var context = canvas.getContext("2d");
var fundo = document.querySelector("#fundo");

canvas.style.backgroundImage=`url(${fundo.src})`;
#fundo { display: none; }
<canvas id="canvas" width="480" height="320"></canvas>

<img src="https://i.ytimg.com/vi/re4_9blE4ts/hqdefault.jpg" id="fundo" />

Since you are using the canvas it would make more sense to "paint" that image directly on the canvas. Example:

document.addEventListener('DOMContentLoaded', _ =>{
  var canvas = document.querySelector("#canvas");
  var context = canvas.getContext("2d");
  var fundo = document.querySelector("#fundo");

  context.drawImage(fundo, 0,0);
}, false);
#fundo { display: none; }
<canvas id="canvas" width="480" height="320"></canvas>

<img src="https://i.ytimg.com/vi/re4_9blE4ts/hqdefault.jpg" id="fundo" />

  • Thank you lazyFox your first alternative worked correctly.

  • And the second no? Consider marking this question as a solution if no more answers emerge.

  • For some reason the 2nd didn’t work....

  • Maybe your image is not loaded yet when the code is executed, I made a small change in the answer code see if it makes a difference in the final result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.