Canvas: Draw backgroundImage of ANOTHER dom element

56 views Asked by At

I have a dom element with a background-image property.

What is the best way to draw that background image on a canvas?

Edit: The only way I can think of doing this is extracting the URL from the background-image property, then loading it in an image object, and drawing that.

1

There are 1 answers

0
AudioBubble On

Yes, extracting the URL for the background-image property is the best way to go. But there are couple of caveats:

  • If the background-image is defined using a CSS rule it won't be available on the style property.
  • There is the shortcut background: as well which can contain color, size etc.
  • The string for the URL may or may not be formatted with surrouding url("") which needs to be stripped off if it is, it can include quotes or not.

The best and more safe way to get the URL independent of if it where set using style attribution or CSS rule, is to use getComputedStyle() on the window object. This will give you a proper formatted strings for that specific style:

var computedRules = window.getComputedStyle(element);

From there get the string formatted by the browser using getPropertyValue():

var urlStr = computedRules.getPropertyValue("background-image");

The result will be something like this depending on browser -

Firefox:

url("http://domain.to/img.png")

Chrome (no quotes):

url(http://domain.to/img.png)

You can use various techniques to strip off the url("") part, from RegEx to step-by-step. The former is sometimes simpler as it can be expanded easily if new criteria must be included, while the latter tend to perform better (but that won't be an issue here).

Example

When put together you can use something like this (you may have to cover other situations when cleaning up the URL than I did in this small example):

var div = document.querySelector("div"),
    url = cleanURL(getComputedStyle(div).getPropertyValue("background-image")),
    img = new Image();

// use async handler for image loading:
img.onload = function() {
  var ctx = document.querySelector("canvas").getContext("2d");
  ctx.drawImage(this, 0, 0);
  // continue from here...
};
img.src = url;

function cleanURL(url) {
  if (!url.length || url === "none") return "";
  var p1 = url.indexOf("("), p2;
  if (p1 > -1) {
    p2 = url.lastIndexOf(")");
    if (p2 > -1) url = url.substring(p1+1, p2);
  }
  p1 = url.indexOf("\"");
  if (p1 > -1) {
    p2 = url.lastIndexOf("\"");
    if (p2 > -1) url = url.substring(p1+1, p2);
  }
  return url
}
div {
  width:200px;height:50px;
  background-image:url(https://i.imgur.com/nq5XI6O.png)
  }
Div w/background-image: <div></div><br>
Canvas:<br><canvas width=200 height=50></canvas>