js实现画三角形
使用Canvas绘制三角形
Canvas是HTML5提供的绘图API,通过JavaScript可以轻松绘制各种图形,包括三角形。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(100, 100); // 起点
ctx.lineTo(150, 150); // 第二个点
ctx.lineTo(50, 150); // 第三个点
ctx.closePath(); // 闭合路径
ctx.stroke(); // 描边
使用CSS绘制三角形
CSS可以通过边框技巧创建三角形,这种方法不需要JavaScript。
function createCSSTriangle() {
const triangle = document.createElement('div');
triangle.style.width = '0';
triangle.style.height = '0';
triangle.style.borderLeft = '50px solid transparent';
triangle.style.borderRight = '50px solid transparent';
triangle.style.borderBottom = '100px solid red';
document.body.appendChild(triangle);
}
使用SVG绘制三角形
SVG是矢量图形标准,可以通过JavaScript动态创建。
function createSVGTriangle() {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', '200');
svg.setAttribute('height', '200');
const triangle = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
triangle.setAttribute('points', '100,10 150,190 50,190');
triangle.setAttribute('fill', 'blue');
svg.appendChild(triangle);
document.body.appendChild(svg);
}
使用WebGL绘制三角形
WebGL提供了更强大的3D图形能力。
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
const vertices = [
-0.5, -0.5, 0.0,
0.5, -0.5, 0.0,
0.0, 0.5, 0.0
];
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
const vertexShaderSource = `
attribute vec3 coordinates;
void main() {
gl_Position = vec4(coordinates, 1.0);
}
`;
const fragmentShaderSource = `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`;
// 创建着色器程序并绘制
// 完整实现需要更多WebGL初始化代码
使用D3.js绘制三角形
D3.js是数据可视化库,也可以用来绘制基本图形。
const svg = d3.select('body').append('svg')
.attr('width', 200)
.attr('height', 200);
svg.append('polygon')
.attr('points', '100,10 150,190 50,190')
.attr('fill', 'green');
每种方法适用于不同场景:Canvas适合动态图形,CSS适合简单UI元素,SVG适合可缩放矢量图形,WebGL适合3D和复杂图形处理,D3.js适合数据可视化集成。







