从左到右,线性跳动
时间: 2023-07-27 11:23:46 浏览: 54
好的,如果您想要实现线性跳动的效果,可以简单修改上述代码实现。具体的实现方法如下:
1. 修改绘制函数
在绘制函数`draw`中,我们需要修改绘制二次贝塞尔曲线的部分,改为绘制直线即可。修改后的代码如下:
```javascript
// 绘制山脉/心电图
const draw = () => {
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y); // 绘制线段
}
ctx.strokeStyle = '#ccc';
ctx.stroke();
// 更新点的位置
for (let i = 0; i < points.length; i++) {
points[i].y += Math.random() * 4 * (Math.random() > 0.5 ? 1 : -1);
points[i].x += 1; // x坐标增加
if (points[i].x > width) {
points[i].x = 0; // 超出画布宽度后,将x坐标置为0
}
}
requestAnimationFrame(draw);
};
```
修改后的代码中,我们使用`ctx.lineTo`绘制直线,而不是二次贝塞尔曲线。同时,在每次更新点的位置时,将每个点的x坐标增加1,模拟线性跳动的效果。当点的x坐标超出画布宽度时,将x坐标置为0,即从左到右循环跳动。
2. 完整代码
```html
<template>
<canvas ref="canvas"></canvas>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
const points = []; // 存储所有的点
// 生成随机点
for (let i = 0; i < width; i += 10) {
const y = height / 2 + Math.random() * height / 4 * (Math.random() > 0.5 ? 1 : -1); // 随机高于平行线或者低于平行线或者持平
points.push({x: i, y: y});
}
// 绘制山脉/心电图
const draw = () => {
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y); // 绘制线段
}
ctx.strokeStyle = '#ccc';
ctx.stroke();
// 更新点的位置
for (let i = 0; i < points.length; i++) {
points[i].y += Math.random() * 4 * (Math.random() > 0.5 ? 1 : -1);
points[i].x += 1; // x坐标增加
if (points[i].x > width) {
points[i].x = 0; // 超出画布宽度后,将x坐标置为0
}
}
requestAnimationFrame(draw);
};
draw();
}
}
</script>
<style scoped>
canvas {
width: 100%;
height: 200px;
}
</style>
```
以上就是实现从左到右线性跳动效果的方法,希望能对您有所帮助。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)