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.
Yes, extracting the URL for the background-image property is the best way to go. But there are couple of caveats:
style
property.background:
as well which can contain color, size etc.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:From there get the string formatted by the browser using
getPropertyValue()
:The result will be something like this depending on browser -
Firefox:
Chrome (no quotes):
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):