我在绘制线性渐变填充矩形时遇到问题。两张截图分别来自 Chrome(左)和 Firefox(右)。正如您所看到的,渐变仅应用于前 170px 的矩形(您可以在右图上看到它更好,因为 Firefox 使用您最后添加的 colorStop 填充了其余部分)。下面的代码确实用 200px 的渐变高度填充了矩形,但我不知道为什么只填充了 170px。高度 = 200,左侧 = 30,顶部 = 30,宽度 = 300,半径 = 3;
//Fill
var lingrad = gcx.createLinearGradient(0, top, 0, Height);
lingrad.addColorStop(0, 'white');
lingrad.addColorStop(0.5, '#66CC00');
lingrad.addColorStop(0.5, 'red');
lingrad.addColorStop(1, 'white');
lingrad.addColorStop(1, 'blue');
gcx.fillStyle = lingrad;
gcx.beginPath();
gcx.lineWidth = 1;
gcx.moveTo(left + radius, top);
gcx.lineTo(left + Width - radius, top);
//Top-right-corner:
gcx.arc(left + Width - radius, top + radius, radius, (Math.PI / 180) * 270, (Math.PI / 180) * 0, false);
gcx.lineTo(left + Width, top + Height - radius);
//Bottom-right-corner:
gcx.arc(left + Width - radius, top + Height - radius, radius, (Math.PI / 180) * 0, (Math.PI / 180) * 90, false);
gcx.lineTo(left + radius, top + Height);
//Bottom-left-corner:
gcx.arc(left + radius, top + Height - radius, radius, (Math.PI / 180) * 90, (Math.PI / 180) * 180, false);
gcx.lineTo(left, top + radius);
//Top-left-corner:
gcx.arc(left + radius, top + radius, radius, (Math.PI / 180) * 180, (Math.PI / 180) * 270, false);
gcx.closePath();
gcx.fill();
感谢您的帮助!
最佳答案
问题是渐变高度不是相对于渐变的 y1-Startpoint 计算的,而是根据 canvas 元素的 y0-Startpoint 计算的。将 y2 的代码更改为 y2 + y1(端点现在是相对于起点计算的),解决了问题。
var lingrad = gcx.createLinearGradient(x1, y1, x2, y2 + y1);
关于javascript - Canvas 绘制带有线性渐变的填充圆 Angular 矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4624614/