D3.js设置SVG图片锚点为中心无效,如何实现中心定位?
解决SVG图片锚点改为中心的问题
SVG的<image>元素并没有anchor属性,所以你添加的attr('anchor','center')不会生效。要实现锚点为中心且适配尺寸变化,有两种实用方法:
方法一:已知图片尺寸时直接计算偏移坐标
如果能确定图片宽高,直接将x、y设为目标坐标减去宽高的一半即可:
var svg = d3.select('body') .append('svg') .attr('width',100) .attr('height',100) .style('border','1px solid red') const imgWidth = 100; const imgHeight = 100; const targetX = 50; const targetY = 50; svg.append("image") .attr("xlink:href", "https://dummyimage.com/100x100/ececec/000000") .attr("width", imgWidth) .attr("height", imgHeight) .attr("x", targetX - imgWidth/2) .attr("y", targetY - imgHeight/2)
方法二:动态获取图片自然尺寸(适配未知/变动的图片)
如果图片尺寸不确定,需等图片加载完成后获取自然宽高再计算偏移:
var svg = d3.select('body') .append('svg') .attr('width',100) .attr('height',100) .style('border','1px solid red') const targetX = 50; const targetY = 50; // 创建临时图片对象获取自然尺寸 const img = new Image(); img.src = "https://dummyimage.com/100x100/ececec/000000"; img.onload = function() { const naturalWidth = this.naturalWidth; const naturalHeight = this.naturalHeight; svg.append("image") .attr("xlink:href", img.src) .attr("width", naturalWidth) .attr("height", naturalHeight) .attr("x", targetX - naturalWidth/2) .attr("y", targetY - naturalHeight/2) }
替代思路:用transform平移
也可以保持x、y为0,通过transform将图片中心移到目标坐标,效果一致:
// 结合动态获取尺寸的写法 img.onload = function() { const naturalWidth = this.naturalWidth; const naturalHeight = this.naturalHeight; svg.append("image") .attr("xlink:href", img.src) .attr("width", naturalWidth) .attr("height", naturalHeight) .attr("transform", `translate(${targetX - naturalWidth/2}, ${targetY - naturalHeight/2})`) }
核心逻辑是:把图片左上角坐标,偏移到「目标中心坐标减去图片宽高的一半」的位置,这样图片中心就会和目标坐标重合,无论图片尺寸如何变化,重新计算该偏移量即可适配。
内容的提问来源于stack exchange,提问作者lucky1928
相关产品推荐
相关产品推荐

