Pan and zoom with text

In response to the previous post I was asked how to make a pan and zoom control that included text. The previous code will work with text, but it will scale the text as you zoom in, which is not necessarily the behaviour you want. Below is the same map of Australia, but now with toponyms. As you zoom in and out the text maintains its position relative the drawing while maintaining its size. This can cause odd effects at extreme scales.

The problem is actually quite tricky and my solution is not particularly elegant. You can see the full code at the bottom of this post. Briefly, it works by having separate groups for the drawing and for the text. The drawing moves as before, but the text elements have to be moved individually when you zoom since their positions relative to one another changes.

for (var i=0; i<nameTranslate.childNodes.length; i++) {
  if (nameTranslate.childNodes[i].nodeName == "text") {
    var child = nameTranslate.childNodes[i];
    var x = parseFloat(child.getAttributeNS(null, "x"));
    var y = parseFloat(child.getAttributeNS(null, "y"));
    var new_x = 250 - (250 - x) * scale;
    var new_y = 150 - (150 - y) * scale;
    child.setAttributeNS(null, "x", new_x);
    child.setAttributeNS(null, "y", new_y);
  }
}

The important lines are 103 and 104 which calculate the new position of the text elements by scaling their distance from the centre of the image. The centre of this image is at (250, 150) - you can changes these values to making the scaling centre on a different point.

Another small point is that the text elements must have the style text-anchor: middle to ensure the centre of the text maintains its position relative to the drawing rather than the beginning.

AttachmentSize
Australia_compass_with_names.svg8.45 KB

Comments

Nice script Peter. I'm currently thinking of making a script that can do text flow and scale up to a minimum px size. I don't want the text to be displayed in anything less than 9 px.

This is really superb. The pan and zoom the image along with the text is what I was looking for. I was adding some labeled diagrams of take machines to my blog. This will be really helpful. Really thank you for sharing this amazing data.

cheap jewellery

Post new comment

The content of this field is kept private and will not be shown publicly.