javascriptcanvas

createLinearGradient without color blending


With the createLinearGradient we can create color gradient and colors blend as per the stop value in addColorStop.

var gradient = ctx.createLinearGradient(0, 0, 0, 400);
    gradient.addColorStop(0, 'blue');   
    gradient.addColorStop(1, 'red');

Can we avoid color blending and have different colors as per the stop value without Blending or Gradient. Maybe this is not possible with createLinearGradient any other API?

I know we can create this using two different fillRect and fillStyle.


Solution

  • I'm not 100% sure of what you mean, but if you want a clear stop from two different colors, you can simply set both colors at the same stop position:

    const canvas = document.querySelector("canvas");
    const ctx = canvas.getContext("2d");
    const grad = ctx.createLinearGradient(0,0,0,150);
    // implicit from -Infinity "green"
    grad.addColorStop(0.33, "green");
    grad.addColorStop(0.33, "yellow"); // same stop as previous color
    grad.addColorStop(0.66, "yellow");
    grad.addColorStop(0.66, "red");    // same stop as previous color
    // implicit to +Infinity "red"
    ctx.fillStyle = grad;
    ctx.fillRect(0,0,300,150);
    canvas.style.height = (150/devicePixelRatio)+'px'; // prevent vertical scaling and resampling, so that users who haven't pinch-zoomed see that the canvas image isn't blurred. this method looks better in more general cases than `image-rendering: pixelated`.
    <canvas></canvas>