js canvas绘制双线箭头直线
时间: 2023-07-17 11:11:35 浏览: 116
canvas绘制的直线动画
要在Canvas上绘制双线箭头直线,你可以按照以下步骤进行操作:
1. 获取到Canvas元素的引用,并创建一个2D上下文对象。
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
```
2. 设置线条的样式,包括线宽和颜色。
```javascript
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
```
3. 绘制直线的起点和终点。
```javascript
const startX = 50;
const startY = 50;
const endX = 200;
const endY = 50;
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(endX, endY);
ctx.stroke();
```
4. 绘制箭头。可以通过绘制三角形来模拟箭头的形状。
```javascript
// 绘制箭头的长度和宽度
const arrowLength = 10;
const arrowWidth = 6;
// 计算箭头的角度和两侧点的坐标
const angle = Math.atan2(endY - startY, endX - startX);
const arrowPoint1X = endX - arrowLength * Math.cos(angle - Math.PI / 6);
const arrowPoint1Y = endY - arrowLength * Math.sin(angle - Math.PI / 6);
const arrowPoint2X = endX - arrowLength * Math.cos(angle + Math.PI / 6);
const arrowPoint2Y = endY - arrowLength * Math.sin(angle + Math.PI / 6);
// 绘制箭头
ctx.beginPath();
ctx.moveTo(endX, endY);
ctx.lineTo(arrowPoint1X, arrowPoint1Y);
ctx.moveTo(endX, endY);
ctx.lineTo(arrowPoint2X, arrowPoint2Y);
ctx.stroke();
// 绘制箭头底部闭合
ctx.beginPath();
ctx.moveTo(arrowPoint1X, arrowPoint1Y);
ctx.lineTo(arrowPoint2X, arrowPoint2Y);
ctx.lineTo(endX, endY);
ctx.closePath();
ctx.fill();
```
完整的代码示例如下:
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
const startX = 50;
const startY = 50;
const endX = 200;
const endY = 50;
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(endX, endY);
ctx.stroke();
const arrowLength = 10;
const arrowWidth = 6;
const angle = Math.atan2(endY - startY, endX - startX);
const arrowPoint1X = endX - arrowLength * Math.cos(angle - Math.PI / 6);
const arrowPoint1Y = endY - arrowLength * Math.sin(angle - Math.PI / 6);
const arrowPoint2X = endX - arrowLength * Math.cos(angle + Math.PI / 6);
const arrowPoint2Y = endY - arrowLength * Math.sin(angle + Math.PI / 6);
ctx.beginPath();
ctx.moveTo(endX, endY);
ctx.lineTo(arrowPoint1X, arrowPoint1Y);
ctx.moveTo(endX, endY);
ctx.lineTo(arrowPoint2X, arrowPoint2Y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(arrowPoint1X, arrowPoint1Y);
ctx.lineTo(arrowPoint2X, arrowPoint2Y);
ctx.lineTo(endX, endY);
ctx.closePath();
ctx.fill();
```
这样就可以在Canvas上绘制双线箭头直线了。记得根据你的需求修改起点和终点的坐标。希望对你有所帮助!
阅读全文