当前位置:首页 > JavaScript

js实现胶囊形状

2026-01-30 22:57:55JavaScript

使用 CSS 和 SVG 实现胶囊形状

胶囊形状可以通过 CSS 的 border-radius 属性或 SVG 的路径绘制实现。以下是几种常见方法:

CSS 方法: 通过设置 border-radius 为高度的一半即可实现胶囊形状。例如:

js实现胶囊形状

.capsule {
  width: 100px;
  height: 50px;
  border-radius: 25px; /* 高度的一半 */
  background-color: #ff6b6b;
}

SVG 方法: 使用 SVG 的 <rect> 元素结合 rxry 属性实现圆角矩形:

<svg width="120" height="60">
  <rect x="10" y="10" width="100" height="40" rx="20" ry="20" fill="#74b9ff"/>
</svg>

动态调整的 JavaScript 实现

若需要通过 JavaScript 动态生成胶囊形状,可以结合 DOM 操作:

js实现胶囊形状

function createCapsule(width, height, color) {
  const capsule = document.createElement('div');
  capsule.style.width = `${width}px`;
  capsule.style.height = `${height}px`;
  capsule.style.borderRadius = `${height / 2}px`;
  capsule.style.backgroundColor = color;
  return capsule;
}

// 使用示例
document.body.appendChild(createCapsule(150, 60, '#55efc4'));

Canvas 绘制胶囊

通过 Canvas 的 arcToarc 方法绘制:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

function drawCapsule(ctx, x, y, width, height, color) {
  const radius = height / 2;
  ctx.beginPath();
  ctx.arc(x + radius, y + radius, radius, Math.PI / 2, 3 * Math.PI / 2);
  ctx.arc(x + width - radius, y + radius, radius, 3 * Math.PI / 2, Math.PI / 2);
  ctx.closePath();
  ctx.fillStyle = color;
  ctx.fill();
}

drawCapsule(ctx, 50, 50, 200, 80, '#a29bfe');

响应式胶囊组件(React 示例)

对于前端框架,可以封装为可复用的组件:

function Capsule({ width, height, color, children }) {
  const style = {
    width: `${width}px`,
    height: `${height}px`,
    borderRadius: `${height / 2}px`,
    backgroundColor: color,
    display: 'inline-flex',
    justifyContent: 'center',
    alignItems: 'center'
  };
  return <div style={style}>{children}</div>;
}

// 使用示例
<Capsule width={120} height={40} color="#fd79a8">按钮</Capsule>

标签: 胶囊形状
分享给朋友: