渐变颜色

线性渐变 var lg= context.createLinearGradient(xStart,yStart,xEnd,yEnd)

线性渐变颜色lg.addColorStop(offset,color)
    xstart:渐变开始点x坐标
    ystart:渐变开始点y坐标
    xEnd:渐变结束点x坐标
    yEnd:渐变结束点y坐标

    offset:设定的颜色离渐变结束点的偏移量(0~1)
    color:绘制时要使用的颜色

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="800" height="850">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>

function draw0(id) {
  var canvas = document.getElementById(id);
  if (canvas == null)
      return false;
  var context = canvas.getContext('2d');
  var g1 = context.createLinearGradient(0, 0, 0, 300);

  g1.addColorStop(0, 'rgb(255,0,0)'); //红  
  g1.addColorStop(0.5, 'rgb(0,255,0)');//绿
  g1.addColorStop(1, 'rgb(0,0,255)'); //蓝

  //可以把lg对象理解成GDI中线性brush
  context.fillStyle = g1;
  //再用这个brush来画正方形
  context.fillRect(0, 0, 400, 300);  
}
draw0("myCanvas");

</script>

</body>
</html>


渐变颜色_第1张图片

径向渐变(发散)var rg=context.createRadialGradient(xStart,yStart,radiusStart,xEnd,yEnd,radiusEnd)

径向渐变(发散)颜色rg.addColorStop(offset,color)
    xStart:发散开始圆心x坐标
    yStart:发散开始圆心y坐标
    radiusStart:发散开始圆的半径
    xEnd:发散结束圆心的x坐标
    yEnd:发散结束圆心的y坐标
    radiusEnd:发散结束圆的半径

    offset:设定的颜色离渐变结束点的偏移量(0~1)
    color:绘制时要使用的颜色

渐变颜色_第2张图片

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="800" height="850">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>

function draw0(id) {
	//同一个圆心画球型
	/*var canvas = document.getElementById(id);
	if (canvas == null)
	return false;
	var context = canvas.getContext('2d');
	var g1 = context.createRadialGradient(200, 150, 0, 200, 150, 100);
	g1.addColorStop(0.1, 'rgb(255,0,0)');  
	g1.addColorStop(1, 'rgb(50,0,0)');
	context.fillStyle = g1;
	context.beginPath();
	context.arc(200, 150, 100, 0, Math.PI * 2, true);
	context.closePath();
	context.fill();*/
	
	//不同圆心看径向渐变模型
	var canvas = document.getElementById(id);
	if (canvas == null)
	return false;
	var context = canvas.getContext('2d');
	var g1 = context.createRadialGradient(100, 150, 10, 300, 150, 50);
	g1.addColorStop(0.1, 'rgb(255,0,0)');
	g1.addColorStop(0.5, 'rgb(0,255,0)');
	g1.addColorStop(1, 'rgb(0,0,255)');
	context.fillStyle = g1;
	context.fillRect(0, 0, 400, 300);
	
	}
draw0("myCanvas");

</script>

</body>
</html>

你可能感兴趣的:(渐变颜色)