简体   繁体   English

使用javascript定位SVG元素

[英]Positioning an SVG element using javascript

I am doing a modification on svg-edit. 我正在对svg-edit进行修改。 I am using a function to make a path element bigger or smaller based on width and height inputs by the user. 我正在使用一个函数,根据用户输入的宽度和高度,使路径元素变大或变小。 The user selects an element and clicks on a button to fire up the function which takes the last known width and heght measurements and then asks from the user the new width and height values. 用户选择一个元素并单击一个按钮以启动该功能,该功能将进行最后一次已知的宽度和高度测量,然后向用户询问新的宽度和高度值。 It then creates a divisor which it uses to create a TRANSFORM MATRIX operation on the element to make it as big as the user wants. 然后,它创建一个除数,该除数用于在元素上创建TRANSFORM MATRIX操作,以使其达到用户所需的大小。

The problem is that when transforming matrices, the elements also changes position. 问题在于,在变换矩阵时,元素也会改变位置。

I want when the user is asked for a width and height also to be asked for x,y position on canvas and then move the selected element to that position. 我希望当用户被要求提供宽度和高度时也被要求在画布上设置x,y位置,然后将所选元素移动到该位置。

Is their a way of repositioning an svg element? 他们是重新定位svg元素的方法吗?

   function changeDimensions() 

    {
  svgNode = svgCanvas.getSelectedElems()[0];

var dims = Raphael.pathBBox(svgNode.getAttribute('d')); 
lasth = parseInt(dims.height); 
lastw= parseInt(dims.width);

var transformw=prompt("Enter your new width");
var transformh=prompt("Enter your new height");
newW=transformw/lastw;
 newH=transformh/lasth; 

svgCanvas.changeSelectedAttribute("transform", "matrix(" + newW + ", 0, 0, " + newH + ", 0, 0)"); svgCanvas.changeSelectedAttribute(“ transform”,“ matrix(” + newW +“,0,0,” + newH +“,0,0)”); svgCanvas.recalculateAllSelectedDimensions(); svgCanvas.recalculateAllSelectedDimensions(); } }

Different svg elements have different attributes that they use to position themselves. 不同的svg元素具有用于定位自身的不同属性。 For example rect's have x and y attributes but circles have cx, and cy. 例如,rect具有x和y属性,而圆具有cx和cy。 Path's do not have separate attributes. 路径没有单独的属性。

However you can probably get what you need from a transform! 但是,您可能可以从转换中获得所需的东西! Most svg elements will accept a transform attribute where you can assign a translation. 大多数svg元素将接受一个transform属性,您可以在其中分配翻译。 Eg 例如

<path d="M10,10L20,100" transform="translate(30,40)"/>

In fact you can probably scale your path with the same transform attribute. 实际上,您可以使用相同的transform属性缩放路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM