canvas创建线性渐变

本文详细介绍了如何使用HTML5 canvas元素创建线性渐变效果,从基本概念到实践应用,包括设置渐变方向、颜色停止点和在画布上应用渐变的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<!--		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-->
<html>
   <head>
     <title>Rectangles</title>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
       <title>线性渐变</title>

      <style>
         #canvas {
            background: #eeeeee;
            border: thin solid cornflowerblue;
         }
      </style>
   </head>

   <body>
      <canvas id='canvas' width='450' height='275'>
         Canvas not supported
      </canvas>

      <script>
      	var canvas=document.getElementById('canvas');
      	context=canvas.getContext('2d');
      	//创建线性渐变  x0 渐变开始点的x坐标,y0渐变开始点的y坐标,x1渐变结束点的x坐标,y1渐变结束点的y坐标
      	gradient=context.createLinearGradient(0,0,0,canvas.height/2);
      	gradient.addColorStop(0,'blue');
      	gradient.addColorStop(0.25,'white');
      	gradient.addColorStop(0.5,'purple');
      	gradient.addColorStop(0.75,'red');
      	gradient.addColorStop(1,'yellow');
      	
      	//设置渐变色
      	context.fillStyle=gradient;
      	context.rect(0,0,canvas.width,canvas.height);
      	//填充渐变色
      	context.fill();
      </script>
   </body>
</html>
演示地址:http://sandbox.runjs.cn/show/pwalehz5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值