Javascript d3 insert image from local file

巧了我就是萌 提交于 2020-01-06 06:00:41

问题


Update: I changed the last two lines to the following.

.append('img')
    .attr('src','images/testimage.png')

But the image is not appearing. There is a broken image in its place so I believe either the file path syntax is incorrect or there's something else I'm not seeing.

Original Post

I'm having trouble rendering an image stored in my local directory via js. The last 2-3 lines of code is where the issue is. I'm not 100% sure if that's the correct notation for the file path (I think it is based on this thread.

d3.select("#solve")
  .append('h2')
  .text("Solve.")

for (var i = 0; i < response.length; i++){

    d3.select("#question")
          .append('p')
          .text(response[i]['id'])
          .append('p')
          .text(response[i]['statement'])
          .append('li')
          .text(response[i]['a1'])
          .append('li')
          .text(response[i]['a2'])
          .append('li')
          .text(response[i]['a3'])
          .append('li')
          .text(response[i]['a4'])
          .append('li')
          .text(response[i]['a5'])
          .append('div')
          .append('svg:image')
          .attr('href', 'file://C:/Users/Bryant/Documents/GitHub/ACT/static/js/images/testimage.png')


}

};

When i inspect the HTML element, this is what I get. However no image appears on the webpage.

<image href="file://C:/Users/Bryant/Documents/GitHub/ACT/static/js/images/testimage.png"></image>

Any help is appreciated, thanks.


回答1:


It seems like you want to add an image element to your div selection using d3js. You don't need to append an svg in order to do this, you can directly append your img element to your div:

const domElement = d3.select("#question");
const imagePath = 'https://cdn.dribbble.com/users/22018/screenshots/2456036/d3_1x.png';
domElement.append('img').attr('src', imagePath);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="question"></div>



回答2:


Instead of:

.append('svg:image')
.attr('href', 'file://C:/Users/Bryant/Documents/GitHub/ACT/static/js/images/testimage.png')

use this (xlink:href attribute in place of href) :

.append('svg:image')
.attr("xlink:href", function() {return "file://C:/Users/Bryant/Documents/GitHub/ACT/static/js/images/testimage.png"})
.attr('width', "50")
.attr('height', "50")


来源:https://stackoverflow.com/questions/50847834/javascript-d3-insert-image-from-local-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!