みかづきブログ その3

本ブログは更新を終了しました。通算140万ユーザーの方に観覧頂くことができました。長い間、ありがとうございました。

👆

引越し先はこちらです!

Canvasで角丸の四角形を描く

愚直にパスを左上から時計回りに一周描くことで角丸の四角形を描く関数をつくりました。

JavaScript

var canvas = document.getElementById("canvas");

drawRect({
    ctx : canvas.getContext("2d"),
    x : 10,
    y : 10,
    width: 120,
    height: 120,
    radius: 26,
    color: "rgba(0, 0, 0, .2)"
});

function drawRect(param) {
    var ctx = param.ctx;
    var x = param.x;
    var y =param.y;
    var width = param.width;
    var height = param.height;
    var radius = param.radius || 0;
    var color = param.color;
    
    ctx.save();
        ctx.fillStyle = color;
        ctx.beginPath();
            ctx.moveTo(x + radius, y);
            ctx.lineTo(x + width - radius, y);
            ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, 0, false);
            ctx.lineTo(x + width, y + height - radius);
            ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5, false);
            ctx.lineTo(x + radius, y + height);
            ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI, false);
            ctx.lineTo(x, y + radius);
            ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5, false);
        ctx.closePath();
        ctx.fill();
    ctx.restore();
}

DEMO