I'm trying to draw an external svg file into a webpage using d3 and make it zoom on scroll. I followed http://bl.ocks.org/mbostock/3892919 but when i add my svg file it remain fixed and doesn't zoom. I will draw several svg so i will have an array like this:
var data = []
data.push({
name: "base",
x: 50,
y: 50,
width: 350,
url: 'https://upload.wikimedia.org/wikipedia/commons/1/15/Svg.svg'
});
and draw it with a function:
function add(elements, offsetX = 0, offsetY = 0) {
for (let e of elements) {
d3.xml(e.url, 'image/svg+xml', function(error, xml) {
if (error) {
console.log('error' + error)
throw error;
}
var svgNode = xml.getElementsByTagName('svg')[0];
d3.select(svgNode).attr('id', e.name)
.attr('x', e.x + offsetX)
.attr('y', e.y + offsetY);
svg.node().appendChild(svgNode);
svg.select('#' + e.name)
.attr('width', e.width);
});
}
}
full jsfiddle
I looked around the pan & zoom examples available and this is what I found. In the zoomed
function, there should be a translate and scale on the elements appended, not just the x and y axis.
So, I created a group where to append the elements:
var elementsToScale = svg.append("g").attr("id", "elementsToScale")
And I added the last lines in the zoomed
function:
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
var translate = d3.event ? d3.event.translate : "0,0"
var scale = d3.event ? d3.event.scale : "1"
svg.select("#elementsToScale").attr("transform", "translate(" + translate + ")" + " scale(" + scale + ")");
}
And then I changed the add
function to append the elements to the elementsToScaleGroup
:
d3.xml(el.url, 'image/svg+xml', function(error, xml) {
if (error) {
console.log('error' + error)
throw error;
}
var svgNode = xml.getElementsByTagName('svg')[0];
d3.select(svgNode).attr('id', e.name)
.attr('x', el.x + offsetX)
.attr('y', el.y + offsetY);
elementsToScale.node().appendChild(svgNode);
elementsToScale.select('#' + el.name)
.attr('width', el.width);
});
Here is a working fiddle .
The only thing left is the tween on the elements appended on reset.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.