Set gradient fill for each feature separately #15739
-
Hi, I found an old version of this example that does exactly this but I wasn't successful in porting it to the latest version of OpenLayers. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
You can do that the same way as with any other style - create a style that applies only to a single feature, and that style has its own pattern or gradient fill. |
Beta Was this translation helpful? Give feedback.
-
I don't know what exactly you are trying to achieve. But this example shows how to create a gradient for the extent of each feature: https://codesandbox.io/p/sandbox/canvas-gradient-pattern-forked-g9ntwf?file=%2Fmain.js%3A53%2C32: // Generate a rainbow gradient
function gradient(feature, resolution) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
var extent = feature.getGeometry().getExtent();
// Gradient starts on the left edge of each feature, and ends on the right.
// Coordinate origin is the top-left corner of the extent of the geometry, so
// we just divide the geometry's extent width by resolution and multiply with
// pixelRatio to match the renderer's pixel coordinate system.
const [x, y] = getTopLeft(extent).map(
(v) => (v / resolution) * DEVICE_PIXEL_RATIO
);
var grad = context.createLinearGradient(
x,
y,
x + (getWidth(extent) / resolution) * DEVICE_PIXEL_RATIO,
y
);
grad.addColorStop(0, "red");
grad.addColorStop(1 / 6, "orange");
grad.addColorStop(2 / 6, "yellow");
grad.addColorStop(3 / 6, "green");
grad.addColorStop(4 / 6, "aqua");
grad.addColorStop(5 / 6, "blue");
grad.addColorStop(1, "purple");
return grad;
} |
Beta Was this translation helpful? Give feedback.
I don't know what exactly you are trying to achieve. But this example shows how to create a gradient for the extent of each feature: https://codesandbox.io/p/sandbox/canvas-gradient-pattern-forked-g9ntwf?file=%2Fmain.js%3A53%2C32: