1.使用strokeRect和fillRect方法绘制矩形
a.strokeRect是绘制一个不填充的矩形
b.fillRect是绘制一个填充的矩形
代码:
<script>
var canvas = document.getElementById(‘canvas‘),
context = canvas.getContext(‘2d‘);context.lineJoin = ‘round‘;
context.lineWidth = 20;context.strokeRect(10, 10, 150, 100);
context.fillRect(180, 10, 150, 100);
</script>
效果如图:
2.通过lineTo绘制矩形
<script>
var canvas = document.getElementById(‘canvas‘),
context = canvas.getContext(‘2d‘);context.lineJoin = ‘round‘;
context.lineWidth = 20;
context.beginPath();
context.moveTo(10, 10);
context.lineTo(160, 10);
context.lineTo(160, 110);
context.lineTo(10, 110);
context.closePath();
context.stroke();context.beginPath();
context.moveTo(180, 10);
context.lineTo(330, 10);
context.lineTo(330, 110);
context.lineTo(180, 110);
context.closePath();
context.fill();
</script>
效果图如下:
[HTML5 Canvas学习]绘制矩形,码迷,mamicode.com