使用 canvas 元素,必须先设置 width 和 height 属性,指定可以绘图的区域大小。
要在这块画布上绘图,需要取得绘图上下文。而取得绘图上下文对象的引用,需要调用 getContext() 方法并传入上下文的名字。传入“2d”,就可以取得2D上下文对象。
与矩形相关的方法包括:fillRect()、strokeRect()、clearRect()。这三个方法都能接收 4 个参数:矩形的x坐标,矩形的y坐标,矩形宽度和矩形高度。这些参数的单位都是像素。
<html>
<body>
<canvas id="drawing" width="500" height="500">A drawing of something</canvas>
<script>
var drawing = document.getElementById("drawing");
// 确认浏览器支持<canvas>元素
if (drawing.getContext) {
var context = drawing.getContext('2d');
// 绘制红色描边矩形
context.lineWidth = 10;
context.lineCap = "butt";
context.lineJoin = "round";
context.strokeStyle = "#ff0000";
context.strokeRect(50, 50, 300,300);
// 绘制半透明蓝色描边矩形
context.lineWidth = 20;
context.lineCap = "butt";
context.lineJoin = "bevel";
context.strokeStyle = "rgba(0, 0, 255, 0.5)";
context.strokeRect(100, 100, 300, 300);
// 清除一个矩形
context.clearRect(150, 40, 100, 100);
}
</script>
</body>
</html>
效果图: