最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Scale SVG around center with plain javascript - Stack Overflow

programmeradmin3浏览0评论

I have a problem maybe understanding well how coordinates work ins SVG. I have a javascript function that scales an svg graphic such as that:

var g = document.getElementById("graph");
var nm = g.getCTM().multiply(k); //k is the scale factor
g.setAttribute("transform", "matrix(" + nm.a + "," + nm.b + "," + nm.c + "," + nm.d + "," + nm.e + "," + nm.f + ")");

The point is that after scaling the center is slightly translated so the graphic loses is "geographic" center. How can I determine which translation I need to have to scale the graphic "around" its center?

Thanks.

I have a problem maybe understanding well how coordinates work ins SVG. I have a javascript function that scales an svg graphic such as that:

var g = document.getElementById("graph");
var nm = g.getCTM().multiply(k); //k is the scale factor
g.setAttribute("transform", "matrix(" + nm.a + "," + nm.b + "," + nm.c + "," + nm.d + "," + nm.e + "," + nm.f + ")");

The point is that after scaling the center is slightly translated so the graphic loses is "geographic" center. How can I determine which translation I need to have to scale the graphic "around" its center?

Thanks.

Share Improve this question edited Dec 13, 2012 at 12:19 Sirko 74.1k19 gold badges155 silver badges190 bronze badges asked Dec 13, 2012 at 12:18 kandankandan 7472 gold badges12 silver badges41 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Have you considered other approaches?

If you just looking for zoom in/out on an svg, it might be easier to do it differently, e.g.: http://www.cyberz/blog/2009/12/08/svgpan-a-javascript-svg-panzoomdrag-library/

I had the same problem a while ago and ended up creating my own zoom using this: https://github./rstacruz/jquery.transit

You basically use css transform scale for a svg wrapper and svg adjusts nicely. You can even animate the zooming.

As I think fits better my purpose and after reading how to do it in the helpful link

http://mons.oreilly./wiki/index.php/SVG_Essentials/Transforming_the_Coordinate_System#The_scale_Transformation

I have changed it to scale the graphic around the position of the mouse when its wheel is scrolled,

If it helps this is the code (using SVGPan's setCTM method):

var svgRoot = document.getElementsByTagName("svg")[0];
var g = svgRoot.getElementById("viewport");

var newp = svgRoot.createSVGPoint();
newp.x = evt.clientX;
newp.y = evt.clientY;
newp = newp.matrixTransform(g.getScreenCTM().inverse());

var oldx = newp.x;
var oldy = newp.y;

//z = scale factor
setCTM(g, g.getCTM().translate(-(oldx*(z-1)),-(oldy*(z-1))).scale(z));
发布评论

评论列表(0)

  1. 暂无评论