canvasタグの使い方

canvasタグはJavaScriptで操作します。

<body onload="draw();">
    <canvas id="canvas" width="xxx" height="xxx"></canvas>
</body>
function draw() {
    let canvas = document.querySelector("#canvas");
    if (canvas.getContext) {
        let ctx = canvas.getContext("2d");

        // 描画
    }
}
ctx.fillRect(x, y, width, height); // 矩形塗りつぶし
ctx.strokeRect(x, y, width, height); // 矩形輪郭
ctx.clearRect(x, y, width, height); // 矩形削除
  • beginPath()→新規パス作成
  • パスメソッドでパス描画
  • closePath()→パスを閉じる
  • stroke()→パスの輪郭をなぞる
  • fill()→パスを塗りつぶす
function draw() {
    let canvas = document.querySelector("#canvas");
    if (canvas.getContext) {
        let ctx = canvas.getContext("2d");

        // 描画
        beginPath();
        moveTo(75, 50); // ペンを移動
        lineTo(100, 75); // パスを描画
        lineTo(100, 25);  // パスを描画
        fill();  // パスを閉じて、塗りつぶし
    }
}
arc(x, y, radius, startAngle, endAngle, counterclockwise);
arcTo(x1, y1, x2, y2, radius);
quadraticCurveTo(cp1x, cp1y, x, y); // 2次ベジェ曲線
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); // 3次ベジェ曲線
  • Path2D
  • SVGパス
目次