当前位置:首页 > JavaScript

js实现胶囊形状

2026-04-04 14:47:00JavaScript

使用CSS和SVG实现胶囊形状

在JavaScript中创建胶囊形状可以通过CSS或SVG实现。以下是几种常见方法:

CSS方法 通过border-radius属性设置椭圆或胶囊形状:

js实现胶囊形状

.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>元素结合rxry属性:

js实现胶囊形状

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适合需要动态绘制的场景。

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

相关文章

js实现胶囊形状

js实现胶囊形状

使用 CSS 和 SVG 实现胶囊形状 胶囊形状可以通过 CSS 的 border-radius 属性或 SVG 的路径绘制实现。以下是两种常见方法: 方法一:纯 CSS 实现 通过设置 bord…

java如何输出形状

java如何输出形状

在Java中输出形状可以通过多种方式实现,常见的方法包括使用循环结构控制字符的排列组合。以下是几种典型形状的实现示例: 输出矩形 通过嵌套循环控制行和列的打印,外层循环控制行数,内层循环控制每行的星…

css各种形状制作

css各种形状制作

CSS 制作矩形 使用 width 和 height 属性定义矩形尺寸,background-color 设置填充色: .rectangle { width: 200px; height:…