js实现渐变
使用CSS线性渐变
在JavaScript中动态创建线性渐变可以通过修改元素的style属性实现。以下示例为元素添加从左到右的红色到蓝色渐变背景:
const element = document.getElementById('target');
element.style.background = 'linear-gradient(to right, red, blue)';
使用CSS径向渐变
径向渐变可通过类似方式实现,以下代码创建从中心向外扩散的圆形渐变:

element.style.background = 'radial-gradient(circle, yellow, green)';
动态控制渐变参数
通过变量控制渐变方向和颜色:
const colors = ['#ff0000', '#00ff00', '#0000ff'];
const angle = '45deg';
element.style.background = `linear-gradient(${angle}, ${colors.join(', ')})`;
使用Canvas绘制渐变
Canvas API提供更精细的渐变控制:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 100);
动画渐变效果
结合CSS动画实现渐变过渡效果:
element.style.transition = 'background 1s ease';
element.style.background = 'linear-gradient(to right, purple, orange)';
响应式渐变调整
监听窗口大小变化动态调整渐变:
window.addEventListener('resize', () => {
const width = window.innerWidth;
element.style.background =
`linear-gradient(${width > 768 ? 'to right' : 'to bottom'}, red, blue)`;
});






