Javascript实现立体金字塔
以下是JavaScript实现立体金字塔的完整源码:
// 创建画布
const canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);
// 获取画笔
const ctx = canvas.getContext("2d");
// 设置立体金字塔的参数
const WIDTH = 200;
const HEIGHT = 200;
const DEPTH = 200;
const ANGLE_X = Math.PI / 4;
const ANGLE_Y = Math.PI / 4;
// 计算顶点坐标
function calculateVertex(x, y, z) {
// 沿X轴旋转
const x1 = x;
const y1 = y * Math.cos(ANGLE_X) - z * Math.sin(ANGLE_X);
const z1 = y * Math.sin(ANGLE_X) + z * Math.cos(ANGLE_X);
// 沿Y轴旋转
const x2 = x1 * Math.cos(ANGLE_Y) + z1 * Math.sin(ANGLE_Y);
const y2 = y1;
const z2 = -x1 * Math.sin(ANGLE_Y) + z1 * Math.cos(ANGLE_Y);
return { x: x2, y: y2, z: z2 };
}
// 绘制三角形
function drawTriangle(vertices, color) {
ctx.fillStyle = color;