js实现胶囊形状
使用CSS和SVG实现胶囊形状
在JavaScript中创建胶囊形状可以通过CSS或SVG实现。以下是几种常见方法:
CSS方法
通过border-radius属性设置椭圆或胶囊形状:

.capsule {
width: 200px;
height: 100px;
border-radius: 50px;
background-color: #4CAF50;
}
JavaScript动态创建:
const capsule = document.createElement('div');
capsule.style.width = '200px';
capsule.style.height = '100px';
capsule.style.borderRadius = '50px';
capsule.style.backgroundColor = '#4CAF50';
document.body.appendChild(capsule);
SVG方法
使用SVG的<rect>元素结合rx和ry属性:

const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', '200');
svg.setAttribute('height', '100');
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute('x', '0');
rect.setAttribute('y', '0');
rect.setAttribute('width', '200');
rect.setAttribute('height', '100');
rect.setAttribute('rx', '50');
rect.setAttribute('ry', '50');
rect.setAttribute('fill', '#4CAF50');
svg.appendChild(rect);
document.body.appendChild(svg);
使用Canvas绘制胶囊形状
通过Canvas 2D API绘制:
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#4CAF50';
// 绘制半圆(左侧)
ctx.beginPath();
ctx.arc(50, 50, 50, Math.PI/2, Math.PI*3/2);
ctx.fill();
// 绘制半圆(右侧)
ctx.beginPath();
ctx.arc(150, 50, 50, Math.PI*3/2, Math.PI/2);
ctx.fill();
// 绘制中间矩形
ctx.fillRect(50, 0, 100, 100);
动态调整胶囊比例
通过JavaScript函数实现可调整比例的胶囊:
function createCapsule(width, height, color) {
const element = document.createElement('div');
element.style.width = `${width}px`;
element.style.height = `${height}px`;
element.style.borderRadius = `${height/2}px`;
element.style.backgroundColor = color;
return element;
}
document.body.appendChild(createCapsule(300, 80, '#FF5722'));
这些方法提供了从简单到灵活的胶囊形状实现方案,可根据具体需求选择CSS、SVG或Canvas方案。CSS方案最适合常规UI元素,SVG适合矢量图形,Canvas适合需要动态绘制的场景。


