js实现矩形
使用 Canvas 绘制矩形
Canvas 是 HTML5 提供的绘图 API,通过 JavaScript 操作可以绘制矩形。
// 获取 Canvas 元素和上下文
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制填充矩形
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 50);
// 绘制描边矩形
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.strokeRect(150, 10, 100, 50);
使用 SVG 创建矩形
SVG 是矢量图形标记语言,可以直接在 HTML 中嵌入矩形元素。

<svg width="300" height="100">
<!-- 填充矩形 -->
<rect x="10" y="10" width="100" height="50" fill="blue" />
<!-- 描边矩形 -->
<rect x="150" y="10" width="100" height="50"
stroke="red" stroke-width="3" fill="none" />
</svg>
使用 CSS 绘制矩形
纯 CSS 可以通过 div 元素和样式来创建矩形效果。

<div class="filled-rect"></div>
<div class="outlined-rect"></div>
<style>
.filled-rect {
width: 100px;
height: 50px;
background-color: blue;
}
.outlined-rect {
width: 100px;
height: 50px;
border: 3px solid red;
margin-top: 10px;
}
</style>
使用 WebGL 绘制矩形
WebGL 提供了更底层的 3D 图形绘制能力,也可以用于 2D 矩形绘制。
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 顶点着色器
const vsSource = `
attribute vec2 aPosition;
void main() {
gl_Position = vec4(aPosition, 0.0, 1.0);
}
`;
// 片段着色器
const fsSource = `
void main() {
gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
}
`;
// 初始化着色器程序
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
const programInfo = {
program: shaderProgram,
attribLocations: {
aPosition: gl.getAttribLocation(shaderProgram, 'aPosition'),
},
};
// 矩形顶点数据
const positions = [
-0.5, 0.5,
0.5, 0.5,
0.5, -0.5,
-0.5, -0.5,
];
// 创建缓冲区并绑定数据
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// 绘制矩形
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(programInfo.program);
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.vertexAttribPointer(
programInfo.attribLocations.aPosition,
2,
gl.FLOAT,
false,
0,
0
);
gl.enableVertexAttribArray(programInfo.attribLocations.aPosition);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
使用 D3.js 绘制矩形
D3.js 是数据可视化库,可以方便地创建和操作 SVG 元素。
// 创建 SVG 容器
const svg = d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 100);
// 添加填充矩形
svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 50)
.attr("fill", "blue");
// 添加描边矩形
svg.append("rect")
.attr("x", 150)
.attr("y", 10)
.attr("width", 100)
.attr("height", 50)
.attr("stroke", "red")
.attr("stroke-width", 3)
.attr("fill", "none");
每种方法适用于不同场景:Canvas 适合动态图形,SVG 适合可缩放矢量图形,CSS 适合简单 UI 元素,WebGL 适合高性能图形,D3.js 适合数据可视化。






