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). 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). The following code does fill the rect with 20开发者_Python百科0px of gradient height, and I don't know why only 170px are filled up. Height = 200, left = 30, top = 30, Width = 300, radius = 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. Changing the code for y2 to y2 + y1 (endpoint is now calculated relative to startpoint), fixed the problem.
var lingrad = gcx.createLinearGradient(x1, y1, x2, y2 + y1);
精彩评论