As I understand it, gradient fills must be specified relative to the canvas element itself (i.e. 0, 0) rather than relative to the shape you're actually filling.
Question: am I right in this assertion, and is there a suggested way around it?
For example (JSFiddle here):
ctx.beginPath();
ctx.rect(40, 50, 100, 70);
var grd = ctx.createLinearGradient(0, 50, 0, 120);
grd.addColorStop(0, "red");
grd.addColorStop(1, "blue");
ctx.fillStyle = grd;
ctx.fill();
There, I make a rectangle. I expected that, to fill it with a gradient starting from the top left of the shape, I would pass 0, 0
as the first two params. It seems I must pass instead the X/Y coordinates of the rectangle relative to the canvas.
This bees an issue if, say, you have an arc built with a quadratic curve, since, without being a Maths genius, you don't know the top position of the curve - only the control point.
As I understand it, gradient fills must be specified relative to the canvas element itself (i.e. 0, 0) rather than relative to the shape you're actually filling.
Question: am I right in this assertion, and is there a suggested way around it?
For example (JSFiddle here):
ctx.beginPath();
ctx.rect(40, 50, 100, 70);
var grd = ctx.createLinearGradient(0, 50, 0, 120);
grd.addColorStop(0, "red");
grd.addColorStop(1, "blue");
ctx.fillStyle = grd;
ctx.fill();
There, I make a rectangle. I expected that, to fill it with a gradient starting from the top left of the shape, I would pass 0, 0
as the first two params. It seems I must pass instead the X/Y coordinates of the rectangle relative to the canvas.
This bees an issue if, say, you have an arc built with a quadratic curve, since, without being a Maths genius, you don't know the top position of the curve - only the control point.
Share Improve this question edited Jun 10, 2015 at 13:28 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 11, 2012 at 18:31 MityaMitya 34.7k13 gold badges69 silver badges124 bronze badges1 Answer
Reset to default 6If you don't know the bounds of the shapes that you're drawing, you're going to have a bad time.
If you're using gradients, especially re-using gradients, it's best to always make your gradients and shapes from the origin and translate them to the locations they are going to be.
Setting up that sort of system will make it so that defining gradients is more or less relative to the size of your objects, but you'll still have to do the bounds calculations yourself.
Here's an example of translating a gradient and shape to make it "relative" to the canvas:
http://jsfiddle/simonsarris/RFgcs/