javascript canvasタグを使用して3次ベジェ曲線を作成する
- 2021.01.09
- javascript
- javascript

javascriptで、canvasタグを使って、3次ベジェ曲線を作成するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
canvasタグ使い方
bezierCurveToを使用すれば、3次ベジェ曲線を作成するを作成することが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/** html **/ <canvas id="cvs"></canvas> /** js **/ // 2D図形を扱う const ctx = cvs.getContext('2d'); // 3次ベジェ曲線 ctx.strokeStyle = '#C82333'; ctx.lineWidth = 2; ctx.beginPath(); // 開始地点 ctx.moveTo(100, 0); // コントロール //ctx.bezierCurveTo //(1つ目のコントロールポイントのX座標, 1つ目のコントロールポイントのY座標,2つ目のコントロールポイントのX座標,2つ目のコントロールポイントのY座標, x座標, y座標); ctx.bezierCurveTo(300, 30, 150, 90, 270, 145); ctx.stroke(); |
サンプルコード
以下は、
「作成」ボタンをクリックすると、canvasタグに3次ベジェ曲線を作成する
サンプルコードとなります。
※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。また、関数はアロー関数化してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> const hoge = () => { // 2D図形を扱う const ctx = cvs.getContext('2d'); // 3次ベジェ曲線 ctx.strokeStyle = '#C82333'; ctx.lineWidth = 2; ctx.beginPath(); // 開始地点 ctx.moveTo(100, 0); // コントロール //ctx.bezierCurveTo //(1つ目のコントロールポイントのX座標, 1つ目のコントロールポイントのY座標,2つ目のコントロールポイントのX座標,2つ目のコントロールポイントのY座標, x座標, y座標); ctx.bezierCurveTo(300, 30, 150, 90, 270, 145); ctx.stroke(); } window.onload = () => { // クリックイベントを登録 btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略 } </script> <body> <div class="main"> <canvas id="cvs"></canvas> <button id="btn" type="button" class="btn btn-info"> 作成 </button> </div> </body> </html> |
3次ベジェ曲線が作成されていることが確認できます。

-
前の記事
javascript シフト演算子を使って2の累乗計算を行う 2021.01.09
-
次の記事
python 文字列が全て数字であるかを判定する 2021.01.09
コメントを書く