js 实现圆角
使用 CSS 实现圆角
在 JavaScript 中可以通过操作 DOM 元素的 style 属性来动态设置圆角。以下是几种常见的实现方式:
// 获取目标元素
const element = document.getElementById('target-element');
// 设置统一的圆角半径(例如 10px)
element.style.borderRadius = '10px';
// 设置不同方向的圆角半径(左上、右上、右下、左下)
element.style.borderRadius = '10px 5px 15px 20px';
// 使用百分比实现圆形(宽高需相等)
element.style.borderRadius = '50%';
使用 Canvas 绘制圆角矩形
通过 Canvas API 可以绘制带有圆角的矩形图形:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
function drawRoundedRect(x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.fillStyle = '#8ED6FF';
ctx.fill();
}
drawRoundedRect(50, 50, 200, 100, 20);
SVG 实现圆角
通过 JavaScript 动态创建 SVG 元素并设置圆角属性:

const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute('width', '300');
svg.setAttribute('height', '200');
const rect = document.createElementNS(svgNS, "rect");
rect.setAttribute('x', '50');
rect.setAttribute('y', '50');
rect.setAttribute('width', '200');
rect.setAttribute('height', '100');
rect.setAttribute('rx', '20'); // 水平圆角半径
rect.setAttribute('ry', '10'); // 垂直圆角半径
rect.setAttribute('fill', '#FF9E7D');
svg.appendChild(rect);
document.body.appendChild(svg);
动态计算圆角值
根据元素尺寸自动计算合适的圆角值:
function adaptiveBorderRadius(element) {
const width = element.offsetWidth;
const height = element.offsetHeight;
const minDimension = Math.min(width, height);
element.style.borderRadius = `${minDimension * 0.1}px`;
}
window.addEventListener('resize', () => {
const box = document.getElementById('adaptive-box');
adaptiveBorderRadius(box);
});
圆角动画效果
使用 JavaScript 实现圆角变化的动画:
function animateBorderRadius(element, start, end, duration) {
const startTime = performance.now();
function update(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const radius = start + (end - start) * progress;
element.style.borderRadius = `${radius}px`;
if (progress < 1) {
requestAnimationFrame(update);
}
}
requestAnimationFrame(update);
}
const animatedElement = document.getElementById('animated-element');
animateBorderRadius(animatedElement, 0, 50, 1000);






