在此jsFiddle中,我D3
与结合使用interact.js
,两者都在进行SVG
。有一个包含矩形和图像的组。组类是可调整大小的,可以正常工作。问题在于,矩形在调整大小后应裁剪图像(即,图像永远不应超出矩形边界),但事实并非如此。我clipPath
为此使用了D3 ,但是它不起作用。问题是什么?
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 200);
var g = svg.append('g')
.attr('class', 'resize-me');
var rect = g.append('rect')
.attr('stroke', 'blue')
.attr('x', 0)
.attr('y', 0)
.attr("width", 200)
.attr("height", 200)
.attr('stroke-width', 2)
.attr('stroke', 'white')
.attr('fill', 'grey');
var image = g.append('image')
.attr('x', 0)
.attr('y', 0)
.attr('width', 128)
.attr('height', 128)
.attr("xlink:href", imageUrl);
interact('.resize-me')
.resizable({
edges: { left: true, right: true, bottom: true, top: true }
})
.on('resizemove', function(event) {
var target = event.target;
var rect = target.childNodes[0];
var img = target.childNodes[1];
var x = (parseFloat(target.getAttribute('endx')) || 0)
var y = (parseFloat(target.getAttribute('endy')) || 0)
rect.setAttribute('width', event.rect.width);
rect.setAttribute('height', event.rect.height);
x += event.deltaRect.left
y += event.deltaRect.top
rect.setAttribute('transform', 'translate(' + x + ', ' + y + ')')
rect.setAttribute('endx', x)
rect.setAttribute('endy', y)
// clip image
svg.append('defs')
.append('clipPath')
.attr('id', 'clip2')
.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', event.rect.width)
.attr('height', event.rect.height);
image.attr("clip-path", "url(#clip2)");
});
您是否希望图像始终扩大以填充灰色框?https://jsfiddle.net/alexander_L/u607w315/12/(用于图像扩展的12版)
另外,<def/>
每次事件触发时,您都将附加标签:
它很快就失控了。
您应该将<def/>
d附加到一些虚拟的单元素数组数据上,并使用d3.js更新模式,或更简单的方法是,您只需<def/>
在源代码中创建标签并每次更新同一标签的属性即可。
您可以一开始就做一次:
var def = svg.append('defs')
.append('clipPath')
.attr('id', 'clip2')
.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', 200)
.attr('height', 200);
然后使用此变量并在活动期间进行更新:
def.attr('x', 0)
.attr('y', 0)
.attr('width', event.rect.width)
.attr('height', event.rect.height);
然后,您可以避免此问题。
https://jsfiddle.net/alexander_L/u607w315/11/(用于图像裁剪的版本11)
您是否想要这种行为:
当灰色框的一维尺寸小于图像尺寸时,图像被裁剪吗?
更新
由于OP注意到原始代码中的一个错误,该错误导致灰色框始终至少恢复到图像的高度或宽度,因此我尝试也解决了此问题。
但是,我还注意到一些奇怪的行为,即框的左上角无法进一步向上延伸或向左延伸,因此我首先进行了修复:https : //jsfiddle.net/alexander_L/u607w315/25/
请参阅新行为的.gif和OP提到的旧错误:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句