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

标签 javascript jquery html css image

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

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

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

然后,我想将该图像加载到 CSS 背景图像属性

.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'

从字里行间看你的评论,“这不会让浏览器下载图像两次吗?”听起来像是一个误解 - 浏览器已经缓存资源,你可以在任何上下文中重用资源 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-background 图像与 img 元素一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113513/

相关文章:

javascript - 带有前导零的数字文字不会产生预期值

javascript - 使用 .attr() 获取多个属性,以使用 "id"从元素中获取 ":checked"和 "this"| jQuery

PHP post ID 下拉语句不是值

javascript - 在输入文本字段中获得选择的最简单方法是什么?

jQuery 连接可排序 - 单击移动无法正常工作

php - 用正则表达式匹配两个标签之间的所有内容?

html - 时髦的 flexbox 高度

javascript - 文件上传后返回空对象 - Apollo graphql

javascript - 电子邮件验证 nodemailer 适用于本地主机但不适用于服务器

javascript - 计算复选框被选中的次数