Created
May 22, 2025 01:24
-
-
Save kyLi18n/dde321251dae2706b85e862864edead3 to your computer and use it in GitHub Desktop.
HTML Canvas 绘制渐变并导出为图片
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
用法:
canvas
标签的属性处设置宽高。ctx.createLinerGradient()
的参数以指定渐变起止点坐标。gradient.addColorStop()
为渐变添加断点并设置颜色和透明度。