Canvas 坐标
HTML Canvas 坐标
Section titled “HTML Canvas 坐标”理解 Canvas 坐标
Section titled “理解 Canvas 坐标”HTML Canvas 是一个二维网格。坐标系始于 Canvas 的左上角。
- x 坐标 向右移动时增加。
- y 坐标 向下移动时增加。
- Canvas 的左上角坐标为 (0,0)。
例如,如果你使用 ctx.fillRect(0, 0, 150, 75);,如前一章所示,这意味着:
- 从 x 坐标
0和 y 坐标0(左上角)开始。 - 绘制一个宽度为
150像素(沿 x 轴方向)、高度为75像素(沿 y 轴方向)的矩形。
坐标示例可视化
Section titled “坐标示例可视化”想象一个宽度为 300 像素、高度为 150 像素的 Canvas (<canvas id="myCanvas" width="300" height="150"></canvas>):
- 点
(0,0)是左上角。 - 点
(300,0)是右上角。 - 点
(0,150)是左下角。 - 点
(300,150)是右下角。 - 点
(150,75)将是此 Canvas 的正中心。
所有绘图操作都使用这些坐标来定位 Canvas 上的元素。
要在 Canvas 上绘制一条直线,你通常使用这些方法:
beginPath(): 开始一个新的绘图路径。在开始绘制新的形状或线条之前调用它是一个好的实践,以避免连接到之前的路径。moveTo(x, y): 将绘图光标(笔)移动到指定的 (x,y) 坐标,不绘制线条。这定义了你的线条或路径的起始点。lineTo(x, y): 从当前的绘图位置到指定的 (x,y) 坐标添加一条直线。stroke(): 使用当前的strokeStyle和lineWidth实际绘制你已定义的路径(例如,线条)到 Canvas 上。
// HTML: <canvas id="lineCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>const lineCanvas = document.getElementById('lineCanvas');const lineCtx = lineCanvas.getContext('2d');
lineCtx.beginPath(); // 开始一个新的路径lineCtx.moveTo(50, 50); // 线条的起始点 (x1, y1)lineCtx.lineTo(250, 100); // 线条的终止点 (x2, y2)lineCtx.strokeStyle = 'blue'; // 设置线条颜色lineCtx.lineWidth = 3; // 设置线条粗细lineCtx.stroke(); // 绘制线条绘制圆形(或弧)
Section titled “绘制圆形(或弧)”要在 Canvas 上绘制一个圆形或弧,你使用 arc() 方法:
beginPath(): 同样,开始一个新的路径很重要。arc(x, y, radius, startAngle, endAngle, anticlockwise): - (x,y): 弧的中心坐标。 -radius: 弧的半径。 -startAngle: 弧开始的角度(以弧度为单位),从正 x 轴沿顺时针方向测量。 -endAngle: 弧结束的角度(以弧度为单位)。 -anticlockwise(可选): 一个布尔值。如果为true,逆时针绘制弧;否则,顺时针绘制(默认为false)。fill()或stroke(): 用于填充圆形或绘制其轮廓。
注意:角度以弧度为单位。将角度(度)转换为弧度,使用公式:radians = degrees * Math.PI / 180。对于一个整圆,startAngle 是 0,endAngle 是 2 * Math.PI。
// HTML: <canvas id="circleCanvas" width="200" height="120" style="border:1px solid #000;"></canvas>const circleCanvas = document.getElementById('circleCanvas');const circleCtx = circleCanvas.getContext('2d');
circleCtx.beginPath();// x=95, y=50, 半径=40, startAngle=0, endAngle=2*PI (整圆)circleCtx.arc(95, 50, 40, 0, 2 * Math.PI);circleCtx.fillStyle = 'green';circleCtx.fill(); // 填充圆形
// 绘制带轮廓的圆形(描边)circleCtx.beginPath();circleCtx.arc(150, 70, 30, 0, 2 * Math.PI);circleCtx.strokeStyle = 'red';circleCtx.lineWidth = 2;circleCtx.stroke(); // 绘制圆形的轮廓