transition.select("image")
.attr("xlink:href", function(d) {
//fix icon error if icon does not exist in folder
return 'assets/64pxBlue/file.png';
// return d.icon
})
.attr("x", function(d) {return d.position_x ? d.position_x : '0px'})
.attr("y", function(d) {return d.position_y ? d.position_y : '-10px'})
.attr("width", function(d) {return d.value ? d.value : '20px'})
.attr("height", function(d) {return d.value ? d.value : '20px'})
}
我正在尝试以PNG形式可视化文件。解析字符串后;它将匹配具有相应png并呈现的字符串。但是,我没有所有可能的png,因此如果我的assets/64pxBlue/目录中不存在默认的png,则需要返回它。
在我的devtools中,有一个GET错误。如何捕获该错误,并在出现错误时返回file.png?
最佳答案
D3没有任何支持此功能的方法,但是您可以使用以下简单的js来实现:
d3.selectAll("img")[0].forEach(function(i, n){
i.onload=imageFound;//on error call this function
i.onerror=imageNotFound;//on success call this function
if (n ==0)
i.src="http://www.w3schools.com/html/pic_mountain.jpg";
else
i.src="http://www.w3schools.com/html/blah-blah.jpg";//set a wrong url
})
function imageFound() {
console.log('That image is found and loaded');
}
function imageNotFound(me) {
//set default url in case image not found
me.target.src="http://www.w3schools.com/tags/smiley.gif";
console.log("defaut image")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<img alt="Mountain View" style="width:304px;height:228px;">
<img alt="Mountain View" style="width:304px;height:228px;">
关于d3.js - 如何捕捉xlink :href errors in D3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36368530/