gpt4 book ai didi

javascript - 将 css 背景图像与 img 元素一起使用

转载 作者:行者123 更新时间:2023-11-27 23:30:30 25 4
gpt4 key购买 nike

是否可以将存储在 img 元素中的图像数据加载到 css background-image 属性中?

例如,假设我们已经将图像数据下载到'img'元素中

var img = Image();
img.src = '/foo/bar'
img.onload = ....

然后,我想将该图像加载到 css background-image 属性

.something {
background-image: img
}

这可能吗?混合使用 image 元素和 css background-image 属性,以便 CSS 可以将 img 元素中的图像数据用作背景图像

最佳答案

Edit: This first answer was only ever meant to address the original question asked around working with an image element. Scroll down for a better alternative to fetching image data.

如果您试图安全地捕获原始数据以供稍后使用,您可以将图像绘制到 canvas 元素上以生成 base-64 编码的数据 URL。尽管此解决方案将受到同源限制。

const getImageData = imageElement => {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = imageElement.width
canvas.height = imageElement.height
ctx.drawImage(imageElement, 0, 0)
return canvas.toDataURL()
}

const img = new Image
img.addEventListener('load', () =>
// assign to some CSS rule
console.log(getImageData(img))
)
img.src = '/foo/bar'

从字里行间看您的评论,“这不会让浏览器下载图像两次吗?” 听起来像是一种误解 - 浏览器已经缓存了资源,您可以在任何上下文中重复使用 Assets URL在您的页面中( HTML/CSS/JS),除非明确规避,否则请相信它们只被下载一次。


或者,将图像作为 Blob 加载会更清晰。

Note: I'm using a CORS proxy here purely to facilitate a runnable example. You probably wouldn't want to pass your own assets through an arbitrary third-party in a production environment.

const getImage = async url => {
const proxy = 'https://cors-anywhere.herokuapp.com/'
const response = await fetch(`${proxy}${url}`)
const blob = await response.blob()
return URL.createObjectURL(blob)
}

const imageUrl =
'https://cdn.sstatic.net/Sites/stackoverflow/' +
'company/img/logos/so/so-logo.png?v=9c558ec15d8a'

const example = document.querySelector('.example')

getImage(imageUrl).then(objectUrl =>
example.style.backgroundImage = `url(${objectUrl})`
)
.example {
min-height: 140px;
background-size: contain;
background-repeat: no-repeat;
}
<div class="example"></div>

关于javascript - 将 css 背景图像与 img 元素一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113513/

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