简体   繁体   English

画布绘制带有线性渐变的圆角矩形

[英]Canvas drawing filled rounded rect with linear gradient

I've got a problem with drawing linear gradient filled rect. 我在绘制线性渐变填充矩形时遇到问题。 The two screenshots are from chrome (left) and Firefox (right). 这两个屏幕截图来自chrome(左)和Firefox(右)。 As you can see, the gradient is only applied to the rect on the first 170px (you could see it better on the right image, because firefox fills up the rest with the colorStop you've added at last). 如您所见,仅将渐变应用于第一个170px的矩形(您可以在正确的图像上更好地看到它,因为firefox用最后添加的colorStop填充了其余部分)。 The following code does fill the rect with 200px of gradient height, and I don't know why only 170px are filled up. 以下代码的确用200px的渐变高度填充了rect,但我不知道为什么只填充170px。 Height = 200, left = 30, top = 30, Width = 300, radius = 3; 高度= 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();

替代文字替代文字

Thanks for help! 感谢帮助!

The problem is that the gradients height is not calculated relative to the y1-Startpoint of the gradient, its calculated from y0-Startpoint of the canvas element. 问题在于,没有相对于渐变的y1-起点计算渐变高度,而是根据画布元素的y0-起点计算渐变高度。 Changing the code for y2 to y2 + y1 (endpoint is now calculated relative to startpoint), fixed the problem. 将y2的代码更改为y2 + y1(现在已相对于起点计算了终点),从而解决了该问题。

var lingrad = gcx.createLinearGradient(x1, y1, x2, y2 + y1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM