how to scale the element by keeping the fixed position in svg

佐手、 提交于 2019-12-03 00:14:51

Scaling is centred on the origin (0, 0), so if your shape is not centred on (0, 0) it will appear to move. To fix this first translate your shape so it is centred on the origin, then scale it, then translate it back:

transform="translate(78.11 -66.75) scale(2) translate(-78.11 66.75)"

Note that the transformations are done in reverse order.

You could simplify things by creating a shape centred on the origin to start with and then scaling and transforming it.

<path id="container_svg_rectsymbol1" fill="red" stroke="Gray" d="M -5 -5 v10 h10 v-10 h-10" transform="translate(78.11 -66.75) scale(3)"/>

You could also convert the transform into matrix, which would be more efficient:

<path opacity="0.5" fill="red" stroke-width="1" stroke="Gray" d="M -5 -5 v10 h10 v-10 h-10" transform="matrix(3 0 0 3 78.11 -66.75)"/>

[EDIT] To use jQuery animate, this should work (scaling from 0 to 1 over 4 seconds):

        var box = element.getBBox();
        var cx = box.x + box.width/2;
        var cy = box.y + box.height/2;

        $(element).animate(
            { scale: 1 },
            { duration: 4000,
              step: function(now, fx) {
                    scaleVal = now;
                    $(element).attr("transform", "translate(" + cx + " " + cy + ") scale(" + scaleVal + ") translate(" + (-cx) + " " + (-cy) + ")");
                } 
            }
        );

OK, now that I have reread your question, it seems that you want to use transform="scale()" and encountering the mysterious "move" also, which is confusing for most beginners learning SVG (me included).

Scaling is measured from the origin(0,0), hence if the object is at location (50,-100), when applying scale(2), the object location is doubled to (50*2, -100*2) => (100, -200). Hence you need to correct this by translate(-50,100).

Using matrix() would be the next area to explore as it is quite intuitive. The above example would require matrix(2 0 0 2 -50 100) to scale and move it back to original. Also with matrix() code, you can perform flip() and mirror() easily with the 2nd and 3rd field. Again you have to translate the length and/or width of object for these two transformation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!