1. 程式人生 > >arcTo畫邊框圓角

arcTo畫邊框圓角

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
    <!-- <meta http-equiv="X-UA-Compatible" content="ie=edge"> -->
    <title>arcTo繪製圓角</title>
    <style>
        #canvas{
            display: block;
            margin: 0 auto;
            border: 1px solid #666;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="600" height="400"></canvas>
</body>
<script>
    var myCanvas = document.getElementById("canvas");
    var ctx = myCanvas.getContext("2d");
    function toRad(d) {
        return d * Math.PI / 180;
    }
    function circleRect(x,y,width,height,r,color) {
        // 儲存之前的繪圖狀態
        ctx.save();
        ctx.beginPath();
        // 繪製四條邊
        ctx.moveTo(x + r, y);
        ctx.lineTo(x + width - r, y);

        ctx.moveTo(x + r, y + height);
        ctx.lineTo(x + width - r, y + height);

        ctx.moveTo(x, y + r);
        ctx.lineTo(x, y + height - r);
    
        ctx.moveTo(x + width, y + r);
        ctx.lineTo(x + width, y + height - r);

        ctx.moveTo(x + r, y);
        ctx.arcTo(x, y, x, y + r, r);

        ctx.moveTo(x + width - r, y);
        ctx.arcTo(x + width, y, x + width, y + r, r);

        ctx.moveTo(x, y + height - r);
        ctx.arcTo(x, y + height, x + r, y + height, r);
        
        ctx.moveTo(x + width - r, y + height);
        ctx.arcTo(x + width, y + height, x + width, y + height - r, r);
        // 傳入顏色,則使用傳入的顏色,否則預設是黑色
        ctx.strokeStyle = color || '#000';
        ctx.stroke();
        // 恢復之前的繪圖狀態
        ctx.restore();
    }

    circleRect(100,100,200,200,50,"red")
</script>
</html>