如何捕获svg图像无法加载D3? [英] How to catch svg image fail to load in D3?
本文介绍了如何捕获svg图像无法加载D3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用D3创建一个包含< image>
svg元素行的可视化。
I am using D3 to create a visualization with rows of <image>
svg elements.
可能有人知道如果图像文件不可用我可以上传替换图像吗?
Could anyone know how I can upload a replacement image if the image file is not available?
var images= imageGroup.append('svg:image')
.attr("xlink:href",function(d,i){
//lines of code to process filename
return "/img/" + filename + ".jpg"
})
推荐答案
这是一个JavaScript问题,然后 d3.js
:
This is more a JavaScript question then d3.js
:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<svg width="100" height="100"></svg>
<script>
// set up svg image tag
var images = d3.select("svg")
.append('svg:image')
.attr('width', 50)
.attr('height', 50);
// create a test image
var imgTest = new Image();
// if it loads successfully add it to the svg image
imgTest.onload = function() {
images.attr("xlink:href", imgTest.src);
}
// if it fails test another image
imgTest.onerror = function() {
imgTest.src = "https://dummyimage.com/50x50/000/fff.png&text=An+Image!"
}
// this will fail
imgTest.src = "https://does.not/exist.png";
</script>
</body>
</html>
这篇关于如何捕获svg图像无法加载D3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文