Canvas线性渐变呈对角线倾斜 如何实现预期垂直渐变效果
问题原因
问题出在createLinearGradient的参数传入错误。
该API接收4个参数,依次为渐变方向线的起点x坐标、起点y坐标、终点x坐标、终点y坐标,颜色过渡会沿着两点连接的直线方向展开。你当前传入的参数是0, 0, 200, 30,对应方向线是从画布(0,0)坐标到(200,30)坐标的斜线,最终渲染的渐变自然呈现对角线倾斜效果。
修复方案
垂直渐变的核心要求是:渐变方向线为垂直线,即起点和终点的x坐标完全一致,仅y坐标沿填充区域的垂直方向延伸。
你当前填充的矩形范围为x从0到200、y从0到30,只需修改创建渐变的代码,将终点x坐标设为和起点一致即可:
var example = document.getElementById('example'); var context = example.getContext('2d'); var grdBnds = [0, 0, 200, 30] // 修正:垂直渐变保持x坐标不变,仅y轴从顶部延伸到底部 var grd = context.createLinearGradient(grdBnds[0], grdBnds[1], grdBnds[0], grdBnds[3]); grd.addColorStop((1/14)*0, "rgb(0, 0, 0)"); grd.addColorStop((1/14)*1, "rgb(191, 191, 191)"); grd.addColorStop((1/14)*2, "rgb(115, 115, 115)"); grd.addColorStop((1/14)*3, "rgb(245, 182, 181)"); grd.addColorStop((1/14)*4, "rgb(147, 252, 253)"); grd.addColorStop((1/14)*5, "rgb(87, 120, 246)"); grd.addColorStop((1/14)*6, "rgb(177, 251, 162)"); grd.addColorStop((1/14)*7, "rgb(80, 176, 51)"); grd.addColorStop((1/14)*8, "rgb(230, 230, 75)"); grd.addColorStop((1/14)*9, "rgb(187, 109, 93)"); grd.addColorStop((1/14)*10, "rgb(235, 51, 35)"); grd.addColorStop((1/14)*11, "rgb(188, 39, 246)"); grd.addColorStop((1/14)*12, "rgb(117, 20, 124)"); grd.addColorStop((1/14)*13, "rgb(191, 191, 191)"); context.fillStyle = grd; context.fillRect(grdBnds[0], grdBnds[1], grdBnds[2], grdBnds[3]);
对应的HTML结构无需修改:
<canvas id="example" width="1000" height="400"></canvas>
补充提示:如果需要实现水平渐变,反向操作即可——保持方向线的y坐标一致,仅x坐标从填充区域左边缘延伸到右边缘,对应写法为
context.createLinearGradient(grdBnds[0], grdBnds[1], grdBnds[2], grdBnds[1])。
内容的提问来源于stack exchange,提问作者SteepAtticStairs
相关产品推荐
相关产品推荐

