<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas图形着色-线性渐变</title>
</head>
<body>
<canvas id="test"></canvas>
<script>
const cvs=document.getElementById('test');
cvs.width=window.innerWidth;
cvs.height=window.innerHeight;
const ctx=cvs.getContext('2d');
/*
1.建立渐变对象,定义渐变的区域
线性渐变 createLinearGradient(x1, y1, x2, y2)
*/
const gr=ctx.createLinearGradient(
50,50,
450,450
);
/*
2.为渐变添加颜色节点
addColorStop(position, color)
*/
gr.addColorStop(0,'green');
gr.addColorStop(0.5,'yellow');
gr.addColorStop(1,'#00abcd');
/*3.为样式赋值*/
ctx.fillStyle=gr;
/*4.绘图*/
ctx.fillRect(
50,50,
400,400
)
</script>
</body>
</html>