要使用HTML5的<canvas>
元素来制作几座相连的山峰,你可以按照以下步骤进行:
- 设置HTML结构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Mountains</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="mountainCanvas" width="800" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
- 编写JavaScript代码 (
script.js
文件):
const canvas = document.getElementById('mountainCanvas');
const ctx = canvas.getContext('2d');
const mountainHeight = 200;
const mountainWidth = 400;
const numMountains = 3;
const spacing = 100;
function drawMountain(x, height, width) {
ctx.beginPath();
ctx.moveTo(x, canvas.height);
// 使用二次贝塞尔曲线绘制山峰
const peakX = x + width / 2;
const peakY = canvas.height - height;
ctx.quadraticCurveTo(peakX, peakY, x + width, canvas.height);
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < numMountains; i++) {
const x = i * (mountainWidth + spacing);
drawMountain(x, mountainHeight, mountainWidth);
}
}
draw();
这段代码首先设置了canvas的ID,然后获取了该canvas的2D渲染上下文。接着,定义了一些常量,如山峰的高度、宽度、数量以及山峰之间的间距。drawMountain
函数负责绘制单个山峰,而draw
函数则负责绘制所有的山峰。最后,调用draw
函数来渲染山峰。
你可以根据需要调整这些参数,以获得不同的山峰形状、大小和位置。此外,你还可以使用更复杂的路径和曲线来创建更逼真的山峰效果。
标签:山峰,canvas,const,几座,ctx,height,width From: https://www.cnblogs.com/ai888/p/18638460