L D L D - 26 days ago 10
Javascript Question

Render background-image to canvas

I have a DIV container with an image set as background-image (specified by url). Is there any way how to redraw this background-image into canvas (without re-contacting or re-downloading from server -- as the content image is once-to-show)?

Answer

Yes. You can get the URL of the background image, request the image file as Blob, create an <img> element, set src to Blob URL of response, at load event of created img element call .drawImage() with img as first parameter.

The background image could be cached, depending on browser settings. If the image is not cached at browser, you can request image first, then set both css background-image and <canvas> using single request.

You can use fetch() or XMLHttpResponse() to request background-image url(), FileReader(), FileReader.prototype.readAsDataURL() to set src of <img> to .result of FileReader at load event.

Check Network tab at DevTools or Developer Tools, the image should be retrieved

(from cache)    

#bg {
  width:50px;
  height:50px;
  background-image:url(http://placehold.it/50x50);
}
<div id="bg"></div>
<br>
<canvas id="canvas" width="50px" height="50px"></canvas>
<script>
  window.onload = function() {
    var bg = document.getElementById("bg");
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var img = new Image;
    img.width = canvas.width;
    img.height = canvas.height;
    img.onload = (e) => ctx.drawImage(e.target,0,0);
    var background = getComputedStyle(bg).getPropertyValue("background-image");
    var src = background.replace(/^url\(|"|\)$/g, "");
    var reader = new FileReader;
    reader.onload = (e) => img.src = e.target.result;
    fetch(src)
    .then(response => response.blob())
    .then(blob => {
      reader.readAsDataURL(blob);     
    })
  }
  </script>