html5 canvas 绘制圆角矩形

2019-01-14  本文已影响0人  antlove
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圆角矩形</title>
    <style>
        body{
            background-color:#eee;
        }
        #canvas{
            background-color:#fff;
            margin-left:10px;
            margin-top:10px;
            -webkit-box-shadow:4px 4px 8px rgba(0,0,0,0.5);
            -moz-box-shadow:4px 4px 8px rgba(0,0,0,0.5);
            -box-shadow:4px 4px 8px rgba(0,0,0,0.5);
        }
    </style>
</head>
<body>

    <canvas id="canvas" width="800" height="600"></canvas>

    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        function roundedRect(x,y,width,height,radius){
            if(width <= 0 || height <= 0){
                ctx.arc(x,y,radius,0,Math.PI*2);
                return;
            }

            ctx.moveTo(x+radius,y);
            ctx.arcTo(x+width,y,x+width,y+height,radius);
            ctx.arcTo(x+width,y+height,x,y+height,radius);
            ctx.arcTo(x,y+height,x,y,radius);
            ctx.arcTo(x,y,x+radius,y,radius);
        }       
        
        function drawRoundedRect(strokeStyle,fillStyle,x,y,width,height,radius){
            ctx.beginPath();
            roundedRect(x,y,width,height,radius);
            ctx.strokeStyle = strokeStyle;
            ctx.fillStyle = fillStyle;
            ctx.stroke();
            ctx.fill();
        }

        drawRoundedRect("pink","red",20,20,100,100,5);
        drawRoundedRect("black","grey",140,20,100,100,5);
        drawRoundedRect("orange","yellow",260,20,100,100,5);
        drawRoundedRect("purple","blue",380,20,100,100,5);
        drawRoundedRect("#f3f4f8","#000",500,20,100,100,5);



    </script>
</body>
</html>
圆角矩形.png
上一篇下一篇

猜你喜欢

热点阅读