2016-04-02 24 views
1
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を持っていないので、資産/ 64pxBlue /ディレクトリに存在しない場合、デフォルトのpngを返す必要があります。D3でxlink:hrefエラーをキャッチするにはどうすればよいですか?

私のdevtoolsには、GETエラーがあります。そのエラーをどのように捕捉し、エラーがあればfile.pngを返しますか?

答えて

0

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) 
 
    \t 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;">

関連する問題