0
1

[test24]SVG ポリゴンの中に線を引く

Posted at

[test24]SVG ポリゴンの中に線を引く

1.基本

1-1.ベースを作る

  • サイズ500*400、背景はライトグレー
<style>
svg{background-Color:lightgray;}
</style>
<svg width=500 height=400 id="svg">
</svg>

1-2.ポリゴンを書く

  • 3点 [100,200],[300,300],[400,100]の黄色い図形を書く
<style>
svg{background-Color:lightgray;}
</style>
<svg width=500 height=400 id="svg">
<polygon points="100,200 300,300 400,100" fill=yellow />
</svg>

1-3.ポリゴンをプログラムで書く

1-2のpolygonをプログラムに落とし込む

<script>
const createPolygon=(points=[],fill=null)=>{
  const svgNS = svg.namespaceURI;
  /**
    * SVG内に新しい要素を追加するにはcreateElementNSで
    * 所定のnamespaceを設定して要素の種類を指定する
    */
  const polygon=document.createElementNS(svgNS,"polygon");
  /**
    * SVG内の要素を属性を追加するにはsetAttributeNSで
    * 第一引数にnullを設定して属性名と値を指定する
    */
  polygon.setAttributeNS(null,'fill',fill);
  const pointsStr=points.map(x=>x.join(",")).join(" ");
  polygon.setAttributeNS(null,"points",pointsStr);
  return polygon;
}
window.addEventListener('DOMContentLoaded', ()=>{
  const points=[[100,200],[300,300],[400,100]];
  const polygon=createPolygon(points,"yellow");
  svg.appendChild(polygon);
});
</script>
<style>
svg{background-Color:lightgray;}
</style>
<svg width=500 height=400 id="svg">
</svg>

1-4.ポリゴンの辺を線分として分解しておく

3ポイントを結ぶそれぞれを線分の形式に変更しておく

points=[[100,200],[300,300],[400,100]];
↓↓↓
lines=[
 {x1:100,y1:200,x2:300,y2:300},
 {x1:300,y1:300,x2:400,y2:100},
 {x1:400,y1:100,x2:100,y2:100}, // 終端から先頭に戻る
 ];

上記を関数に起こすとこう

const createLines=points=>points.reduce((x,y,z,w)=>{
 const nextPoint=w[w.length==z+1?0:z+1];
 const x1=y[0];
 const y1=y[1];
 const x2=nextPoint[0];
 const y2=nextPoint[1];
 return x.concat({x1,y1,x2,y2});
 },[]);
const points=[[100,200],[300,300],[400,100]];
const lines=createLines(points);
console.log(lines);
0
1
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
1