使用HTML5 Canvas绘制圆角矩形及相关的一些应用举例

2019-01-28 15:11:49于丽

圆角矩形是由四段线条和四个1/4圆弧组成,拆解如下。
2016322111336083.jpg (600×425)

因为我们要写的是函数而不是一个固定的圆角矩形,所以这里列出的是函数需要的参数。分析好之后,直接敲出代码。

JavaScript Code复制内容到剪贴板
  1. <!DOCTYPE html>    <html lang="zh">   
  2. <head>        <meta charset="UTF-8">   
  3.     <title>圆角矩形</title>        <style>   
  4.         body { background: url("./images/bg3.jpg") repeat; }           #canvas { border: 1px solid #aaaaaa; display: block; margin: 50px auto; }   
  5.     </style>    </head>   
  6. <body>    <div id="canvas-warp">   
  7.     <canvas id="canvas">            你的浏览器居然不支持Canvas?!赶快换一个吧!!   
  8.     </canvas>    </div>   
  9.    <script>   
  10.     window.onload = function(){            var canvas = document.getElementById("canvas");   
  11.         canvas.width = 800;            canvas.height = 600;   
  12.         var context = canvas.getContext("2d");            context.fillStyle = "#FFF";   
  13.         context.fillRect(0,0,800,600);      
  14.         drawRoundRect(context, 200, 100, 400, 400, 50);            context.strokeStyle = "#0078AA";   
  15.         context.stroke();        }   
  16.        function drawRoundRect(cxt, x, y, width, height, radius){   
  17.         cxt.beginPath();            cxt.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);   
  18.         cxt.lineTo(width - radius + x, y);            cxt.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);   
  19.         cxt.lineTo(width + x, height + y - radius);            cxt.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2);   
  20.         cxt.lineTo(radius + x, height +y);            cxt.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI);   
  21.         cxt.closePath();        }   
  22. </script>    </body>   
  23. </html>