Accepted answer

Do you want the image to always expand to fill the grey box? (version 12 for image expanding)

enter image description here

Also, you are appending <def/> tags every time the event fires:

enter image description here

It gets quickly out of hand.

You should either attach the <def/> to some dummy one element array data and use the d3.js update pattern or simpler you could just create the <def/> tag in your source code and update the attribute of that same tag each time.

You can do it once at the start:

var def = svg.append('defs')
           .attr('id', 'clip2')
           .attr('x', 0)
           .attr('y', 0)
           .attr('width', 200)
           .attr('height', 200);

And then use this variable and update during your event:

def.attr('x', 0)
           .attr('y', 0)
           .attr('width', event.rect.width)
           .attr('height', event.rect.height);

Then you avoid this issue. (version 11 for image clipping)

Do you want this behaviour:

enter image description here

The image is clipped when the grey box is smaller in one dimension than the image?


Since the OP noticed a bug in the original code which causes the grey box to always snap back to at least the height or width of the image, I tried to also solve this problem.

However, I also noticed some odd behaviour, that the top left corner of the box could not be extended further up or left so I fixed that first:

See the .gif of the new behaviour and the old bug the OP mentioned:

enter image description here

Related Query

More Query from same tag