0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

d3.jsで矢印を操作する

Posted at

の続き。これでできたpath

<path d="M180,80 l0,-30 l15,0 l-15,-30 l-15,30 l15,0" />

をd3.jsで作るにはどうすればいいのだろう?教えて、ChatGPT先生!

// SVG要素の幅と高さを設定
const width = 220;
const height = 270;

// SVGコンテナを作成
const svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height);

// パスのデータを定義
const pathData = "M180,80 l0,-30 l15,0 l-15,-30 l-15,30 l15,0";

// <path>要素を追加
svg.append("path")
  .attr("d", pathData)
  .attr("id", "arrow");

へー、前回作ったパスデータをじかにテキストで定義して、d要素にattrするだけで作れるのか。ChatGPT先生からは線の幅とか色とかも教えてくれたけど、idをつけてcssにまとめた。

せっかくJavaScriptになったので、変数を使って沢山の矢印を描いてみる。それにあたって、ちょっとpathの始点と終点を逆にすることにした。始点だけ絶対座標で指定している。始点を真ん中にすることで、回転の中心も同じ座標になるし、地図投影したときも、たぶん、矢印の中心だけ座標変換して、矢の大きさとか形とかはSVG上の相対ピクセルで表せたままになると思う。

JavaScriptでクラスの配列を書くのははじめてなので、うごくかどうかどきどき。

var arrowwidth2 = 2.5
var arrowheight = 5
var linelength = 5

var DataSet2 = [{ x: 30, y:250, r:215 },
                { x: 70, y:250, r:250 },
                { x: 70, y:210, r:295 },
                { x: 70, y:170, r:310 },
                { x:110, y:210, r:190 },
                { x:110, y:170, r:240 },
                { x:150, y:210, r:200 },
                { x:150, y:170, r:266 }];
svg.selectAll(".arrowsmall")
   .data(DataSet2)
   .enter()
   .append("path")
   .attr("d",function(d,i){
         return "M" + d.x + "," + d.y +
         " l" + arrowwidth2 + ",0"+
         " l-" + arrowwidth2 + ",-" + arrowheight +
         " l-" + arrowwidth2 + "," + arrowheight + 
         " l" + arrowwidth2 + ",0" + 
         " l0," + linelength ;
   })
   .attr("transform", function(d,i){
         return "rotate(" + d.r + "," + d.x + "," + d.y + ")";
   })
   .attr("class", "arrowsmall");

Web キャプチャ_11-8-2023_204640_localhost.jpeg

満足!

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?