js实现线条
使用 Canvas 绘制线条
Canvas API 提供了一种在网页上绘制图形的方式。通过 getContext('2d') 获取绘图上下文,使用 beginPath() 开始路径,moveTo() 设置起点,lineTo() 设置终点,最后用 stroke() 绘制线条。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
使用 SVG 绘制线条
SVG 是一种基于 XML 的矢量图形格式,可以通过 <line> 元素绘制线条。设置 x1, y1 为起点坐标,x2, y2 为终点坐标,stroke 为线条颜色,stroke-width 为线条宽度。
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "200");
svg.setAttribute("height", "200");
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.setAttribute("x1", "0");
line.setAttribute("y1", "0");
line.setAttribute("x2", "200");
line.setAttribute("y2", "100");
line.setAttribute("stroke", "black");
svg.appendChild(line);
document.body.appendChild(svg);
使用 CSS 绘制线条
CSS 可以通过 border 或 linear-gradient 模拟线条效果。例如,创建一个 div 元素,设置其高度为 1px,背景为渐变或纯色。
const div = document.createElement('div');
div.style.width = '200px';
div.style.height = '1px';
div.style.background = 'linear-gradient(to right, black, black)';
document.body.appendChild(div);
使用 WebGL 绘制线条
WebGL 是一种基于 OpenGL ES 的 3D 图形 API,适用于高性能图形渲染。通过创建着色器程序,定义顶点数据,调用 gl.drawArrays() 绘制线条。
const canvas = document.getElementById('myCanvas');
const gl = canvas.getContext('webgl');
const vertexShaderSource = `
attribute vec2 a_position;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
}
`;
const fragmentShaderSource = `
void main() {
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
}
`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [0, 0, 1, 1];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
const positionAttributeLocation = gl.getAttribLocation(program, 'a_position');
gl.enableVertexAttribArray(positionAttributeLocation);
gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.LINES, 0, 2);
使用第三方库绘制线条
第三方库如 D3.js 或 Three.js 提供了更高级的图形绘制功能。例如,使用 D3.js 的 d3.line() 方法生成路径数据,结合 SVG 绘制复杂线条。

import * as d3 from 'd3';
const data = [[0, 0], [100, 50], [200, 100]];
const lineGenerator = d3.line();
const pathData = lineGenerator(data);
const svg = d3.select('body').append('svg').attr('width', 200).attr('height', 200);
svg.append('path').attr('d', pathData).attr('stroke', 'black').attr('fill', 'none');






