利用HTML5 Canvas API绘制矩形的超级攻略

2019-01-28 15:19:14王冬梅
  •         drawRect(context, 150, 50, 50, 50, "red", 5, "blue");            drawRect(context, 250, 50, 50, 50, "green", 5, "red");   
  •         drawRect(context, 350, 50, 50, 50, "yellow", 5, "black");        }   
  •        function drawRect(cxt, x, y, width, height, fillColor, borderWidth, borderColor){   
  •         cxt.beginPath();            cxt.moveTo(x, y);   
  •         cxt.lineTo(x + width, y);            cxt.lineTo(x + width, y + height);   
  •         cxt.lineTo(x, y + height);            cxt.lineTo(x, y);   
  •         cxt.closePath();      
  •         cxt.lineWidth = borderWidth;            cxt.strokeStyle = borderColor;   
  •         cxt.fillStyle = fillColor;      
  •         cxt.fill();            cxt.stroke();   
  •     }    </script>   
  • </body>    </html>   
  • </body>    </html>  

    运行结果:
    2016321105735875.jpg (850×500)

    使用rect()方法绘制矩形
    犹豫绘制矩形是常用的方法,所以在Canvas API中已经帮我们封装好了一个绘制矩形的方法——rect()。这个方法接收4个参数x, y, width, height,实际调用时也就是

    JavaScript Code复制内容到剪贴板
    1. context.rect(x,y,width,height);  

    基于此,我们帮刚才封装的方法优化一下。

    JavaScript Code复制内容到剪贴板