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>
运行结果:

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