HTML5 canvas overlay transparent gradients

I'm creating a color picker in HTML5 like the gradient below

Color gradient

It consists of three elements:

  1. A solid red background color (must be changeable)
  2. A black – transparent gradient from bottom to top
  3. A white – transparent gradient from the left to right

I have managed to create a single gradient and a single color, but I can't figure out how to overlay the solid color and two gradients together. How can I accomplish this?

(I could provide my code but it's pretty generic and wouldn't be useful)


You can overlay two gradients on top of each other:

Fiddle demo

Horizontal gradient

Going from white to the color (HUE degree) you want to use with 100% saturation and 50% lightness:

var grH = ctx.createLinearGradient(0, 0, ctx.canvas.width, 0);
grH.addColorStop(0, '#fff');
grH.addColorStop(1,  'hsl(' + hue + ', 100%, 50%)');

ctx.fillStyle = grH;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

Horizontal gradient


Going from black bottom to transparent at top.

var grV = ctx.createLinearGradient(0, 0, 0, ctx.canvas.height);
grV.addColorStop(0, 'rgba(0,0,0,0)');
grV.addColorStop(1,  '#000');

ctx.fillStyle = grV;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

Vertical gradient


Drawing the horizontal first and then the vertical on top will result in this:

HUE Palette

As in the demo it's easy to create a slider to update the hue palette. You don't need to re-create the black to transparent gradient as in the demo - just cache it to an off-screen canvas and re-use it for each update as that gives you a bit more performance.

Hope this helps.