Skip to content

Instantly share code, notes, and snippets.

@kyLi18n
Created May 22, 2025 01:24
Show Gist options
  • Save kyLi18n/dde321251dae2706b85e862864edead3 to your computer and use it in GitHub Desktop.
Save kyLi18n/dde321251dae2706b85e862864edead3 to your computer and use it in GitHub Desktop.
HTML Canvas 绘制渐变并导出为图片
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gradient</title>
</head>
<body>
<canvas id="canvas" width="1920" height="1080"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, canvas.height, 0, 0);
gradient.addColorStop(0, 'rgba(0, 0, 0, 1)');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const image = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = image;
link.download = 'gradient.png';
link.click();
</script>
</body>
</html>
@kyLi18n
Copy link
Author

kyLi18n commented May 22, 2025

用法:

  • canvas 标签的属性处设置宽高。
  • 修改 ctx.createLinerGradient() 的参数以指定渐变起止点坐标。
  • 通过 gradient.addColorStop() 为渐变添加断点并设置颜色和透明度。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment