LoginSignup
21

More than 5 years have passed since last update.

SVGの2次ベジェ曲線の制御点をドラッグで動かすサンプル

Posted at

デモ

スクリーンショット

quadratic-bezier-curve.png

メモ

マウスイベント座標をSVG座標に変換

以下の関数で変換します。

function getClientPointInSVG(ev) {
  var p, m;

  p = svg.createSVGPoint();
  p.x = ev.clientX;
  p.y = ev.clientY;

  m = dragElem.getScreenCTM();
  return p.matrixTransform(m.inverse());
}

ドラッグ開始時にオフセットをとっておく

mousedownイベントで制御点とマウスイベントの点のずれを保存しておきます。mousemoveイベントでは、そのずれを維持しつつ制御点を移動します。

どの要素にイベントハンドラをセットするか

  • mousedown: 制御点(ドラッグ対象)
  • mousemove, mouseup: svg要素

mousemoveとmouseupのハンドラをsvg要素ではなく制御点につけてしまうと、マウスを素早く動かして制御点から外れるとドラッグが止まってしまって良くなかったです。

参考

以下のページを参考にしました。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21