gpt4 book ai didi

javascript - 使用 Javascript(可能使用 Canvas )获取背景图像的 urldata

转载 作者:行者123 更新时间:2023-11-28 19:04:48 26 4
gpt4 key购买 nike

假设有一个 DIV 元素并且它具有 CSS background-image 属性。

我想用 Javascript 获取背景图片的 urldata(base64)。

我可以获得 IMG 元素的 urldata,但是这个怎么样?

谢谢。

最佳答案

可以通过window.getComputedStyle获取background-image属性的值,然后创建 Canvas 和图像,将值应用到图像的src,绘制到 Canvas 上,最后得到数据? =°

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 中也不工作)

关于javascript - 使用 Javascript(可能使用 Canvas )获取背景图像的 urldata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4001380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com