使用带有img元素的css-background图像

问题描述 投票:2回答:2

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

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

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

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

.something {
  background-image: img
}

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

javascript jquery html css image
2个回答
1
投票

编辑:这个第一个答案只是为了解决围绕使用图像元素的原始问题。向下滚动以获取更好的替代方法来获取图像数据。

如果您试图安全地捕获稍后要使用的原始数据,可以将图像绘制到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加载会更干净。

注意:我在这里使用CORS代理纯粹是为了方便一个可运行的例子。您可能不希望通过生产环境中的任意第三方传递您自己的资产。

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>

1
投票

你可以用JQuery做到这一点

var img = new Image();
img.src = 'http://placehold.it/350x150';
$('div').css('background-image', 'url('+img.src+')');
div {
  height: 150px;
  width: 300px;
  background-size: cover;
  background-position: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

或者纯粹的Javascript

var img = new Image();
img.src = 'http://placehold.it/350x150';
document.getElementById('element').style.backgroundImage = "url("+img.src+")";
div {
  height: 150px;
  width: 300px;
  background-size: cover;
  background-position: center;
}
<div id="element"></div>
© www.soinside.com 2019 - 2024. All rights reserved.