Home > Software design >  add image node to center point not work as expected
add image node to center point not work as expected

Time:11-19

Below code put image at (50,50), the anchor point is left top corner. How can I change the anchor point to image center, image dimension maybe changed, so if just change (50,50) to (0,0) will work for this image, but not work if image dimension changed.

I try add anchor to center but not work.

var svg = d3.select('body')
.append('svg')
.attr('width',100)
.attr('height',100)
.style('border','1px solid red')
.attr('transform','translate(0,0)')

svg.append("image")
  .attr("xlink:href", "https://dummyimage.com/100x100/ececec/000000")
  .attr("x", 50)
  .attr("y", 50)
  .attr('anchor','center')
<script src="https://unpkg.com/[email protected]/dist/d3.min.js"></script>

CodePudding user response:

According to the MDN documentation for SVG Image, image has no anchor attribute. After the SVG is initially layed out, you could use get the size of the SVG and the size of the image and do it manually. Something like so:

let s = d3.select(svg);
let svg_width = s.attr("width");
let svg_height = s.attr("height");

let img = s.select("image").node();
let rect = img.getBoundingClientRect();
let img_width = rect.right - rect.left;
let img_height = rect.bottom - rect.top;

img.setAttribute("x", (svg_width - img_width)/2)
img.setAttribute("y", (svg_height - img_height)/2)
  • Related