使用Javascript获取背景图像的URL数据(可能使用画布)
假设有一个DIV元素,它具有CSS背景图像属性 我想用Javascript获取背景图像的urldata(base64) 我可以得到IMG元素的URL数据,但是这个怎么样使用Javascript获取背景图像的URL数据(可能使用画布),javascript,html,css,canvas,Javascript,Html,Css,Canvas,假设有一个DIV元素,它具有CSS背景图像属性 我想用Javascript获取背景图像的urldata(base64) 我可以得到IMG元素的URL数据,但是这个怎么样 谢谢。您可以通过窗口获取背景图像属性的值。getComputedStyle,然后创建画布和图像,将该值应用于图像的src,在画布上绘制,最后获取数据=° function getBgImageData(el,callback) { var url, image, canvas = document.c
谢谢。您可以通过
窗口获取背景图像属性的值。getComputedStyle
,然后创建画布和图像,将该值应用于图像的src,在画布上绘制,最后获取数据=°
function getBgImageData(el,callback) {
var url,
image,
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// Allows el to be an element or an id
if(typeof el==='string') {
el = document.getElementById(el);
}
// Gets the value of the background-image property
url = window.getComputedStyle(el,null).backgroundImage;
// Removes the url("") part
url = url.substring(5,url.length-2);
// Creates the image
image = new Image();
image.src = url;
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
// Draws the image
ctx.drawImage(image,0,0);
if(callback) {
// Passes the data to the callback function
callback(canvas.toDataURL());
}
};
}
getBgImageData('someId',function(data) {
alert(data);
});
(
getComputedStyle
在IE中不起作用,但Canvas也不起作用)您可以使用窗口获取背景图像属性的值。getComputedStyle
,然后创建画布和图像,将该值应用于图像的src,在画布上绘制,最后获取数据=°
function getBgImageData(el,callback) {
var url,
image,
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// Allows el to be an element or an id
if(typeof el==='string') {
el = document.getElementById(el);
}
// Gets the value of the background-image property
url = window.getComputedStyle(el,null).backgroundImage;
// Removes the url("") part
url = url.substring(5,url.length-2);
// Creates the image
image = new Image();
image.src = url;
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
// Draws the image
ctx.drawImage(image,0,0);
if(callback) {
// Passes the data to the callback function
callback(canvas.toDataURL());
}
};
}
getBgImageData('someId',function(data) {
alert(data);
});
(
getComputedStyle
在IE中不起作用,但Canvas也不起作用)如果映像托管在不同的域上(即使在同一域但不同的子域上),这不会引发安全异常吗?我使用了权限(它不是web应用程序)另一个重要的问题是创建图像元素是否会重新加载实际图像(或从缓存中使用它)。我现在要测试它。@ArtBIT:是的,实际上,我想它可能会引发安全异常,运行此代码时使用“file://...“url或跨域url@Ozgur:如果你想强制浏览器重新加载它(而不是从缓存中使用它),你可以在url中添加一个随机参数image.src=url+(新日期()).getTime()
如果映像托管在不同的域(即使在同一域但不同的子域上)上,这不会引发安全异常吗?我有利用权限(它不是web应用程序)。另一个重要的问题是创建映像元素是否会重新加载实际映像(或从缓存中使用它)。我现在要测试它。@ArtBIT:是的,实际上,我想它可能会引发安全异常,运行此代码时使用“file://...“url或跨域url@Ozgur:如果你想强制浏览器重新加载它(而不是从缓存中使用它),你可以在url中添加一个随机参数image.src=url+(新日期()).getTime()代码>