Html5中使用canvas(画布)绘制矩形的实例

绘制矩形 | canvas.getContext(), fillRect(), fillStyle, lineWidth, strokeStyle, strokeRect(), clearRect() canvas/shape/rectangle.html

 <!DOCTYPE HTML> <html> <head>     <title>在 canvas 上绘制矩形的 demo</title> </head> <body>     <canvas id="canvas" width="300" height="360" style="background-color: rgb(222, 222, 222)">         您的浏览器不支持 canvas 标签     </canvas>     <br/>     <button type="button" onclick="drawIt();">在画布上绘制一些矩形</button>     <button type="button" onclick="clearIt();">清除画布</button>     <script type="text/javascript">         var canvas = document.getElementById('canvas')         if (canvas.getContext) {             alert("您的浏览器支持 canvas 标签");         } else {             alert("您的浏览器不支持 canvas 标签");         }         /*          * canvas.getContext("2d") - 获取画布标签上的 2D 上下文对象(HTML DOM CanvasRenderingContext2D 对象),其拥有多种绘制图像的方法。          */         var ctx = canvas.getContext('2d');         function drawIt() {             clearIt();             /*              * context.fillRect(x, y, w, h) - 绘制一个有填充色的矩形,默认填充色为 0x000000              *   x - 矩形左上角的 x 坐标              *   y - 矩形左上角的 y 坐标              *   w - 矩形的宽              *   h - 矩形的高              */             ctx.fillRect(0, 0, 100, 100);             /*              * context.fillStyle - 指定填充色的颜色值              *              * 颜色值示例如下:              *   Color Name - "green"              *   #rgb - "#0f0"              *   #rrggbb = "#00ff00"              *   rgb(0-255, 0-255, 0-255) - rgb(0, 255, 0)              *   rgb(0.0%-100.0%, 0.0%-100.0%, 0.0%-100.0%) - rgb(0%, 100%, 0%)              *   rgba(0-255, 0-255, 0-255, 0.0-1.0) - rgb(0, 255, 0, 1)              *   rgba(0.0%-100.0%, 0.0%-100.0%, 0.0%-100.0%, 0.0-1.0) - rgb(0%, 100%, 0%, 1)              */             ctx.fillStyle = "#0f0";             ctx.fillRect(120, 0, 100, 50);             /*              * context.lineWidth - 笔划的宽度,默认值是 1.0。              *    注意看本 Demo,笔划的宽度为 10,可以明显的看出其中心线为笔划的路径,画布外的图像不予显示              * context.strokeStyle - 指定笔划的颜色值              * context.strokeRect(x, y, w, h) - 绘制一个不填充的矩形              *   x - 矩形左上角的 x 坐标              *   y - 矩形左上角的 y 坐标              *   w - 矩形的宽              *   h - 矩形的高              */             ctx.lineWidth = 10;             ctx.strokeStyle = "rgb(0, 0, 0)";             ctx.strokeRect(0, 120, 100, 100);             // 绘制一个填充色半透明的矩形             ctx.fillStyle = "rgba(0, 255, 0, 0.3)";             ctx.fillRect(0, 240, 100, 100);         }         function clearIt() {             /*              * context.clearRect(x, y, w, h) - 将指定的矩形区域上的图像全部清除              */             ctx.clearRect(0, 0, 300, 360);             ctx.fillStyle = "Black";             ctx.strokeStyle = "Black";             ctx.lineWidth = 1;         }     </script> </body> </html>

转载于猿2048:→《Html5中使用canvas(画布)绘制矩形的实例》

评论

暂无评论