js实现圆角
使用CSS的border-radius属性
在JavaScript中操作CSS的border-radius属性是最直接的方法。通过修改元素的style属性,可以动态设置圆角:
const element = document.getElementById('targetElement');
element.style.borderRadius = '10px'; // 统一设置四个角
element.style.borderRadius = '10px 5px 20px 30px'; // 分别设置左上、右上、右下、左下
通过类名切换样式
定义CSS类并利用JavaScript切换类名,实现圆角效果:

.rounded {
border-radius: 8px;
}
.circle {
border-radius: 50%;
}
const box = document.querySelector('.box');
box.classList.add('rounded'); // 添加圆角
box.classList.replace('rounded', 'circle'); // 切换为圆形
动态计算圆角值
结合JavaScript计算能力,实现动态圆角逻辑:

const element = document.querySelector('.dynamic-element');
const width = element.offsetWidth;
element.style.borderRadius = `${width / 2}px`; // 根据宽度设置为圆形
使用Canvas绘制圆角图形
通过Canvas API绘制带圆角的形状:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const x = 50, y = 50, width = 100, height = 60, radius = 10;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + height, radius);
ctx.arcTo(x + width, y + height, x, y + height, radius);
ctx.arcTo(x, y + height, x, y, radius);
ctx.arcTo(x, y, x + width, y, radius);
ctx.closePath();
ctx.fillStyle = 'blue';
ctx.fill();
SVG实现圆角
通过JavaScript动态生成带圆角的SVG元素:
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('rx', '15'); // 水平圆角半径
rect.setAttribute('ry', '15'); // 垂直圆角半径
rect.setAttribute('width', '100');
rect.setAttribute('height', '80');
rect.setAttribute('fill', 'green');
svg.appendChild(rect);
document.body.appendChild(svg);






