I'm using D3 library to create drawing application.
I need to draw object (circle for simplicity) on the coordinates where user clicked. Problem is when user uses the pan & zoom and moves the viewport.
Then object is places on wrong position (I guess the problem is event coordinates are relative to svg element and not g, so they are calculated without proper transformation).
$('svg').on('click', function(event) {
d3.select('#content-layer').append('circle')
.attr('r', 10)
.attr('cx', event.offsetX)
.attr('cy', event.offsetY)
.attr('stroke', 'black')
.attr('fill', 'white');
});
var zoomBehavior = d3.behavior.zoom()
.scaleExtent([1, 10])
.on('zoom', () => {
var translate = "translate(" + d3.event.translate + ")";
var scale = "scale(" + d3.event.scale + ")";
d3.select('#content-layer').attr("transform", translate + scale);
});
d3.select('svg').call(zoomBehavior);
I tried to add on click callback to g element, but it is not working (I guess it doesn't have any size?).
Here is jsfiddle:
https://jsfiddle.net/klinki/53ftaw7r/
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…