js实现画三角形
使用Canvas绘制三角形
Canvas是HTML5提供的绘图API,通过JavaScript调用可以绘制各种图形,包括三角形。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 开始绘制路径
ctx.beginPath();
// 移动到第一个顶点
ctx.moveTo(100, 100);
// 连接到第二个顶点
ctx.lineTo(300, 100);
// 连接到第三个顶点
ctx.lineTo(200, 300);
// 闭合路径
ctx.closePath();
// 设置填充颜色
ctx.fillStyle = 'red';
// 填充三角形
ctx.fill();
// 设置描边颜色
ctx.strokeStyle = 'black';
// 描边三角形
ctx.stroke();
使用SVG绘制三角形
SVG是矢量图形格式,可以直接在HTML中嵌入使用。
<svg width="400" height="400">
<polygon points="100,100 300,100 200,300"
fill="red"
stroke="black"
stroke-width="2"/>
</svg>
使用CSS绘制三角形
CSS可以通过边框技巧创建三角形效果。
<div class="triangle"></div>
<style>
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
</style>
使用WebGL绘制三角形
WebGL提供了更底层的图形渲染能力。
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 顶点着色器
const vsSource = `
attribute vec4 aPosition;
void main() {
gl_Position = aPosition;
}
`;
// 片段着色器
const fsSource = `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`;
// 初始化着色器程序
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// 定义三角形顶点
const vertices = [
0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0
];
// 创建缓冲区
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// 绘制三角形
gl.drawArrays(gl.TRIANGLES, 0, 3);
使用D3.js绘制三角形
D3.js是数据可视化库,也可以用于绘制图形。

const svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 400);
svg.append("path")
.attr("d", "M100,100 L300,100 L200,300 Z")
.style("fill", "red")
.style("stroke", "black");
每种方法适用于不同场景:Canvas适合动态图形,SVG适合可缩放矢量图形,CSS适合简单UI元素,WebGL适合3D或高性能图形,D3.js适合数据可视化。






