如何在我的SVG中显示一个占位符图像,直到加载实际图像? [英] How can I display a placeholder image in my SVG until the real image is loaded?

查看:451
本文介绍了如何在我的SVG中显示一个占位符图像,直到加载实际图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用D3.js来渲染包含光栅图像的节点的图形。

I'm using D3.js to render a graph with nodes containing raster images.

var mainscreenURL = s3_base_url + viewController + "/screenshot.jpeg";
svg.select(".mainScreen").transition().attr("height",0).remove();

svg.append("image").attr("xlink:href", mainscreenURL)
        .attr("width", mainScreenW)
        .attr("height", mainScreenH)
        .attr("x", (w / 2) - (mainScreenW / 2)) 
        .attr("y", (h / 2) - (mainScreenH / 2)) 
        .attr("class", "mainScreen")
        .attr("id", viewController)
}); 

其中有些图片非常大,所以HTTP请求大量的时间。我无法缓存图片,因为它们是动态生成的。

Some of these images are pretty large, so the HTTP requests (made implicitly by the browser) can take a substantial amount of time. I can't cache the images, since they're dynamically generated.

如果这是常规HTML,我会显示一个占位符图片,然后将其交换成功完成HTTP get请求后的真正的事情。但由于这是SVG,没有明确的请求,我最终得到一个讨厌的破碎的图像,然后替换为真实的东西。

If this were regular HTML, I'd show a placeholder image, and then swap it out for the real thing upon successful completion of the HTTP get request. But since this is SVG, there is no explicit request, and I end up with a nasty broken image which is then replaced with the real thing.

有任何事件

推荐答案

查看相关:是否可以在SVG中监听图片加载事件?

我不能得到原生的 addEventListener 方法工作,但它看起来像你可以设置 onload 属性(至少在Chrome中有效):

I couldn't get the native addEventListener approach to work, but it looks like you can just set the onload attribute (works in Chrome, at least):

svg.append("image")
    .attr('onload', function() {
         alert('loaded');
    })
    .attr("xlink:href", mainscreenURL);

请参阅fiddle: http://jsfiddle.net/dKxH9/

See fiddle: http://jsfiddle.net/dKxH9/

这篇关于如何在我的SVG中显示一个占位符图像,直到加载实际图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆