js实现菱形
使用 CSS 和 JavaScript 绘制菱形
在网页中实现菱形可以通过多种方式,以下是几种常见的方法:
使用 CSS 的 transform 属性
通过旋转正方形元素来创建菱形:
.diamond {
width: 100px;
height: 100px;
background-color: #3498db;
transform: rotate(45deg);
}
<div class="diamond"></div>
使用 CSS 的 clip-path 属性
更灵活的方法是使用 clip-path 直接定义菱形形状:

.diamond {
width: 100px;
height: 100px;
background-color: #e74c3c;
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}
使用 JavaScript 动态创建菱形
通过 JavaScript 动态计算并设置样式:
function createDiamond(width, height, color) {
const diamond = document.createElement('div');
diamond.style.width = `${width}px`;
diamond.style.height = `${height}px`;
diamond.style.backgroundColor = color;
diamond.style.transform = 'rotate(45deg)';
document.body.appendChild(diamond);
}
createDiamond(100, 100, '#2ecc71');
使用 Canvas 绘制菱形
对于更复杂的图形操作,可以使用 Canvas API:

const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
canvas.width = 200;
canvas.height = 200;
ctx.fillStyle = '#9b59b6';
ctx.beginPath();
ctx.moveTo(100, 0);
ctx.lineTo(200, 100);
ctx.lineTo(100, 200);
ctx.lineTo(0, 100);
ctx.closePath();
ctx.fill();
使用 SVG 创建菱形
SVG 是另一种创建矢量图形的有效方式:
<svg width="200" height="200">
<polygon points="100,0 200,100 100,200 0,100" fill="#f1c40f"/>
</svg>
响应式菱形设计
为了使菱形适应不同屏幕尺寸,可以使用相对单位:
.diamond-responsive {
width: 20vw;
height: 20vw;
background-color: #1abc9c;
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}
每种方法都有其适用场景:CSS 方法简单高效,适合静态元素;JavaScript 方法适合动态生成;Canvas 和 SVG 适合更复杂的图形需求。






