Canvas 线性渐变

来源:互联网 发布:记录工作时间的软件 编辑:程序博客网 时间:2024/06/06 20:16
一 介绍
渐变可以填充在矩形, 圆形, 线条, 文本等等, 各种形状可以自己定义不同的颜色。
以下用来设置Canvas的线性渐变:
createLinearGradient(x,y,x1,y1) - 创建线条渐变。
当我们使用渐变对象,必须使用两种或两种以上的停止颜色。
addColorStop()方法指定颜色停止,参数使用坐标来描述,可以是0至1。
使用渐变,设置fillStyle或strokeStyle的值为渐变,然后绘制形状,如矩形,文本,或一条线。
 
二 代码
<!DOCTYPE html><html><head><meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" /><meta http-equiv="Content-Type" content="text/html; charset=GBK" /><title> 线性渐变 </title></head><body><h2> 线性渐变 </h2><canvas id="mc" width="400" height="280"style="border:1px solid black"></canvas><script type="text/javascript">// 获取canvas元素对应的DOM对象var canvas = document.getElementById('mc');// 获取在canvas上绘图的CanvasRenderingContext2D对象var ctx = canvas.getContext('2d');ctx.save();ctx.translate(30 , 20);// 创建线性渐变lg = ctx.createLinearGradient(0 , 0 , 160 , 80);// 向线性渐变上添加颜色lg.addColorStop(0.2 , "#f00");lg.addColorStop(0.5 , "#0f0");lg.addColorStop(0.9 , "#00f");// 设置使用线性渐变作为填充颜色ctx.fillStyle = lg;// 填充一个矩形ctx.fillRect(0 , 0 , 160 , 80);// 恢复坐标系统ctx.restore();// 平移坐标系统ctx.translate(280 , 160)ctx.beginPath();// 添加圆弧ctx.arc(0 , 0  , 80 , 0 , Math.PI * 2 , true);ctx.closePath();ctx.lineWidth = 12;// 再次创建线性渐变lg2 = ctx.createLinearGradient(-40 , -40 , 80 , 50);// 向线性渐变上添加颜色lg2.addColorStop(0.1 , "#ff0");lg2.addColorStop(0.4 , "#0ff");lg2.addColorStop(0.8 , "#f0f");// 设置使用线性渐变作为边框颜色ctx.strokeStyle = lg2;ctx.stroke();</script></body></html>
 
三 运行结果

 
原创粉丝点击