javascript - Canvas 绘制带有线性渐变的填充圆 Angular 矩形

标签 javascript html canvas

我在绘制线性渐变填充矩形时遇到问题。两张截图分别来自 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();

alt text alt text

感谢您的帮助!

最佳答案

问题是渐变高度不是相对于渐变的 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/

相关文章:

html - 您可以使用 Canvas 获取页面的 "screenshot"吗?

javascript - 在 html5 Canvas 上绘制多个粒子元素而无需渲染终止

javascript - 仅当没有其他事件同时触发时才触发 Javascript 单击/触摸事件?

javascript - Jquery标签值

html - 覆盖 Outlook 中电子邮件标题图像的默认边距/填充

html - 使用 flexbox 的级联网格布局

javascript - 输入值更改导致字体导入

javascript - document.cookie : Works in localhost but Returns Empty on Web Hosting 问题

html - 忽略 CSS 填充

javascript - HTML5 Canvas : Get Event when drawing is finished