原生js制作按箭头方向流动的线
时间: 2023-10-31 10:05:21 浏览: 79
Cesium边界流动线效果
5星 · 资源好评率100%
可以使用 Canvas 和原生 JavaScript 实现按箭头方向流动的线。下面是实现步骤:
1. 获取 Canvas 元素和上下文对象
```
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
```
2. 定义线条颜色和宽度
```
ctx.strokeStyle = "red"; // 线条颜色
ctx.lineWidth = 2; // 线条宽度
```
3. 定义线条的起始点和结束点
```
var startX = 50; // 起始点 x 坐标
var startY = 50; // 起始点 y 坐标
var endX = 200; // 结束点 x 坐标
var endY = 50; // 结束点 y 坐标
```
4. 定义箭头大小和颜色
```
var arrowSize = 10; // 箭头大小
var arrowColor = "black"; // 箭头颜色
```
5. 定义箭头的绘制函数
```
function drawArrow(fromX, fromY, toX, toY) {
var angle = Math.atan2(toY - fromY, toX - fromX);
ctx.beginPath();
ctx.moveTo(toX, toY);
ctx.lineTo(toX - arrowSize * Math.cos(angle - Math.PI / 6), toY - arrowSize * Math.sin(angle - Math.PI / 6));
ctx.moveTo(toX, toY);
ctx.lineTo(toX - arrowSize * Math.cos(angle + Math.PI / 6), toY - arrowSize * Math.sin(angle + Math.PI / 6));
ctx.strokeStyle = arrowColor;
ctx.stroke();
}
```
6. 定义更新线条位置的函数
```
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
endX += 2; // 每次更新 x 坐标
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(endX, endY);
ctx.stroke();
drawArrow(startX, startY, endX, endY); // 绘制箭头
requestAnimationFrame(update); // 循环更新
}
```
7. 调用更新函数
```
update();
```
完整代码示例:
```
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
var startX = 50;
var startY = 50;
var endX = 200;
var endY = 50;
var arrowSize = 10;
var arrowColor = "black";
function drawArrow(fromX, fromY, toX, toY) {
var angle = Math.atan2(toY - fromY, toX - fromX);
ctx.beginPath();
ctx.moveTo(toX, toY);
ctx.lineTo(toX - arrowSize * Math.cos(angle - Math.PI / 6), toY - arrowSize * Math.sin(angle - Math.PI / 6));
ctx.moveTo(toX, toY);
ctx.lineTo(toX - arrowSize * Math.cos(angle + Math.PI / 6), toY - arrowSize * Math.sin(angle + Math.PI / 6));
ctx.strokeStyle = arrowColor;
ctx.stroke();
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
endX += 2;
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(endX, endY);
ctx.stroke();
drawArrow(startX, startY, endX, endY);
requestAnimationFrame(update);
}
update();
```
阅读全文