Gradient fill relative to shape position, not canvas position?

Viewed 2615

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 becomes 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.

1 Answers
Related