Trying to rotate and transform SVG path - do I need trigonometry calculations?

六月ゝ 毕业季﹏ 提交于 2019-12-04 13:45:15

I think I've made roughly what you want: http://dl.dropbox.com/u/169269/resistor.svg

Click and drag on the resistor to scale and rotate it to that mouse position. In this version, the line thickness and circles also scale, but it shouldn't be too difficult to avoid that.

It does require trigonometry and transformations. The key part is the drag function, which I explain in more detail at: http://www.petercollingridge.co.uk/interactive-svg-components/draggable-svg-element

function drag(evt)
{
   if(selected_element != 0)
   {
      var resistor_x = 200;
      var resistor_y = 100;
      var mouse_x = evt.pageX;
      var mouse_y = evt.pageY;

      dx = resistor_x - mouse_x;
      dy = resistor_y - mouse_y;

      d = Math.sqrt(dx*dx + dy*dy);    // Find distance to mouse
      theta = 90+Math.atan2(dy, dx)*180/Math.PI;    //Find angle to mouse in degrees

      transform = "translate(200, 100) rotate(" + theta + ") scale(" + d/310 + ")" ;
      selected_element.setAttributeNS(null, "transform", transform);
   }
}

Note that this code assumes the resistor is 310 pixels long and rotating about (200, 100). Scaling and rotation transformations work centred on (0,0), so you should draw the resistor with the static point at (0,0) and then translate it to where you want.

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