【WebGL之巅】00-使用canvas绘制2d矩形

By yesmore on 2021-07-22
阅读时间 1 分钟
文章共 336
阅读量

对应《WebGL编程指南》代码:00-HelloCanvas2d

知识点

  1. canvas绘图机制:上下文。要在<canvas>上绘制图像,须先获取绘图上下文,“2d”代表我们要绘制二维图形。
  2. fillstyle:设置或返回用于填充绘画的颜色、渐变或模式。
  3. 使用填充颜色填充矩形。
    fillRect(x,y,width,height)
1
2
3
4
参数:x    矩形左上角的 x 坐标
y 矩形左上角的 y 坐标
width 矩形的宽度
height 矩形的高度

实例

HelloCanvas2d.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Clear canvas</title>
</head>

<body onload="main()">
<canvas id="mycanvas" width="400" height="400">
Please use the browser supporting "canvas"
</canvas>
<script src="HelloCanvas2d.js"></script>
</body>
</html>

HelloCanvas2d.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//HelloCanvas2d.js
function main() {
//获取<canvas>标签
var canvas = document.getElementById("mycanvas");
//如果没找到<canvas>标签,则输出错误信息
if (!canvas) {
console.log('Failed to retrieve the <canvas> element.');
return;
}

// canvas绘图机制:上下文。要在<canvas>上绘制图像,须先获取绘图上下文,“2d”代表我们要绘制二维图形。
// 注意区分‘2d’大小写
var ctx = canvas.getContext("2d");


ctx.fillStyle = "rgba(0,100,0,1)";
ctx.fillRect(120, 10, 150, 150);
}

Tips: Please indicate the source and original author when reprinting or quoting this article.