canvas绘制动态山脉
时间: 2023-08-28 20:07:59 浏览: 81
要绘制动态山脉,可以使用 canvas 的绘图方法和 JavaScript 的定时器来实现。以下是一个简单的示例代码:
HTML:
```html
<canvas id="mountains"></canvas>
```
CSS:
```css
#mountains {
width: 100%;
height: 400px;
}
```
JavaScript:
```javascript
const canvas = document.getElementById("mountains");
const ctx = canvas.getContext("2d");
const colors = ["#F44336", "#9C27B0", "#2196F3", "#4CAF50", "#FFC107"]; // 山脉颜色
let mountains = []; // 存储山脉信息的数组
let speed = 2; // 山脉移动速度
let lastTimestamp = 0; // 上一次绘制的时间戳
// 初始化山脉
function initMountains() {
mountains = [];
for (let i = 0; i < 5; i++) {
const mountain = {
height: Math.random() * 200 + 100,
color: colors[Math.floor(Math.random() * colors.length)],
distance: i * 200,
};
mountains.push(mountain);
}
}
// 绘制山脉
function drawMountain(mountain) {
const { height, color, distance } = mountain;
ctx.beginPath();
ctx.moveTo(distance - 200, canvas.height);
ctx.lineTo(distance, canvas.height - height);
ctx.lineTo(distance + 200, canvas.height);
ctx.fillStyle = color;
ctx.fill();
}
// 绘制所有山脉
function drawMountains() {
mountains.forEach((mountain) => drawMountain(mountain));
}
// 移动山脉
function moveMountains(timestamp) {
const deltaTime = timestamp - lastTimestamp;
lastTimestamp = timestamp;
const distance = deltaTime * speed;
mountains.forEach((mountain) => (mountain.distance -= distance));
if (mountains[0].distance < -200) {
mountains.shift();
const newMountain = {
height: Math.random() * 200 + 100,
color: colors[Math.floor(Math.random() * colors.length)],
distance: mountains[3].distance + 200,
};
mountains.push(newMountain);
}
}
function animate(timestamp) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawMountains();
moveMountains(timestamp);
requestAnimationFrame(animate);
}
initMountains();
requestAnimationFrame(animate);
```
这段代码会生成一个 canvas 元素,并在其中绘制动态的山脉。可以通过调整 `speed` 变量的值来控制山脉的移动速度。
阅读全文