简体   繁体   中英

Gradient fill relative to shape position, not canvas position?

As I understand it, gradient fills must be specified relative to the canvas element itself (ie 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.

If 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.net/simonsarris/RFgcs/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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