javascriptに関するメモです。
80 views
これまで、ブラウザで図形を描くには HTML5 の canvas
を使うのが一般的だと思っていました。しかし、実は HTML には SVG
という仕組みがあり、HTML の中に直接図形を描くことができる ことを知りました。
以下のコードは、SVG で円、四角、線を描くシンプルな例です。
<svg width="300" height="200">
<circle cx="100" cy="100" r="50" fill="blue" />
<rect x="150" y="50" width="100" height="100" fill="red" />
<line x1="10" y1="10" x2="200" y2="100" stroke="black" stroke-width="2" />
</svg>
このコードを HTML 内に書くと、次のような図形が表示されます。
<circle>
) → cx=100, cy=100
の位置に半径 r=50
<rect>
) → x=150, y=50
の位置に 100x100
サイズ<line>
) → (10,10)
から (200,100)
へ引かれるcanvas
とは違い、描画コードをそのまま HTML に書ける。fill
, stroke
, opacity
などのスタイルを適用可能。onclick
, onmouseover
などでインタラクティブな要素を作れる。以下のコードをコピーして .html
ファイルとして保存し、ブラウザで開くと実際に動作を確認できます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG の基本</title>
</head>
<body>
<h1>SVG のサンプル</h1>
<svg width="300" height="200">
<circle cx="100" cy="100" r="50" fill="blue" />
<rect x="150" y="50" width="100" height="100" fill="red" />
<line x1="10" y1="10" x2="200" y2="100" stroke="black" stroke-width="2" />
</svg>
</body>
</html>
SVG では、基本的な図形だけでなく、さまざまな絵やデザイン を描くことができます。以下に、SVG で作れる代表的なものを紹介します。
✅ 円 (<circle>
)
✅ 四角 (<rect>
)
✅ 線 (<line>
)
✅ 多角形 (<polygon>
)
✅ 楕円 (<ellipse>
)
✅ 自由曲線 (<path>
)
<svg width="300" height="200">
<circle cx="50" cy="50" r="40" fill="blue" />
<rect x="120" y="30" width="80" height="80" fill="red" />
<line x1="10" y1="150" x2="200" y2="150" stroke="black" stroke-width="3" />
<polygon points="150,10 180,80 120,80" fill="green" />
<ellipse cx="250" cy="50" rx="40" ry="20" fill="purple" />
</svg>
✅ <path>
を使うと、自由な曲線やカスタム図形を作れる!
<svg width="300" height="200">
<path d="M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80" stroke="black" fill="transparent"/>
</svg>
💡 M, C, S はそれぞれ「移動」「曲線」「スムーズ曲線」を表す。
✅ SVG の <text>
を使うと、図形と一緒に文字を描画できる!
<svg width="300" height="200">
<text x="50" y="100" font-size="20" fill="black">Hello, SVG!</text>
</svg>
✅ SVG はロゴやアイコンにも使える!
<svg width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="45" stroke="black" stroke-width="3" fill="yellow"/>
<circle cx="35" cy="40" r="5" fill="black"/>
<circle cx="65" cy="40" r="5" fill="black"/>
<path d="M35 60 Q50 80, 65 60" stroke="black" stroke-width="3" fill="none"/>
</svg>
👆 これは シンプルなスマイルアイコン です。
✅ 折れ線グラフ・棒グラフ・円グラフ なども描ける!
<svg width="300" height="200">
<rect x="10" y="50" width="40" height="100" fill="blue"/>
<rect x="60" y="80" width="40" height="70" fill="red"/>
<rect x="110" y="30" width="40" height="120" fill="green"/>
</svg>
Page 15 of 16.
すぺぺぺ
本サイトの作成者。
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
ChatGPTで自動プログラム作成に取り組み中。
https://www.osumoi-stdio.com/novel/