L D L D - 1 year ago 139
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 Source

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 {
<div id="bg"></div>
<canvas id="canvas" width="50px" height="50px"></canvas>
  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;
    .then(response => response.blob())
    .then(blob => {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download