彩虹效果。"/>
微信小程序canvas渐变,实现彩虹效果。
微信小程序提供了两种渐变的方式:
createLinearGradient(x,y,x1,y1)创建一个线性的渐变。
x,y 起点坐标
x1,y1 终点坐标
createCircularGradient(x,y,r)创建一个从圆心开始的渐变。
x,y 圆心坐标
r 半径
创建了渐变对象之后,必须添加两个或者两个以上的渐变点;
addColorStop(position, color)方法用于指定颜色渐变点的位置和颜色,位置必须位于0到1之间。
一般用setFillStyle()来设置渐变,然后进行画图描述。
使用 createLinearGradient()
const ctx = wx.createCanvasContext( 'myCanvas')// Create linear gradient const grd = ctx.createLinearGradient( 0, 120, 120, 0)
grd.addColorStop( 0, '#FFFF00') grd.addColorStop( 1, '#FF0000') // Fill with gradient ctx.setFillStyle(grd); //将渐变色渲染入正方形 ctx.fillRect( 20, 20, 120, 120); //起点坐标为(20,20),长宽都为120px的正方形 ctx.draw();
使用 createCircularGradient()
const ctx = wx.createCanvasContext( 'myCanvas')// Create circular gradient const grd = ctx.createCircularGradient( 170, 170, 150); grd.addColorStop( 0.79, '#fff') grd.addColorStop( 0.81, '#8B00FF') grd.addColorStop( 0.83, '#0000FF') grd.addColorStop( 0.85, '#00FFFF') grd.addColorStop( 0.87, '#00FF00') grd.addColorStop( 0.89, '#FFFF00') grd.addColorStop( 0.93, '#FF7F00') grd.addColorStop( 0.95, '#FF0000') grd.addColorStop( 1, '#fff') // Fill with gradient ctx.setFillStyle(grd) //将渐变色渲染入矩形 ctx.fillRect( 20, 20, 300, 120) //起点坐标为(20,20),长300px宽120px的矩形 ctx.draw()
补充:addColorStop的position为渐变点的位置,该位置是颜色设置的最中心处。
该文如有描述不当,烦请各位道友指摘。
更多推荐
微信小程序canvas渐变,实现彩虹效果。
发布评论