Question

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)

Était-ce utile?

La solution

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

Vertical

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

Result

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.

Autres conseils

I do not think that the color picker would be "correct" using the method you came up with. Because the white-transparent gradient would make the left bottom corner white but it should be black.

I created a jsfiddle based on this answer. It is still tilted but I think you can figure this out yourself:

function draw(hue){
    var canvas = document.getElementById("hsl-square");
    var ctx = canvas.getContext('2d');
    for(row=0; row<=100; row++){
        var grad = ctx.createLinearGradient(0, 0, 100,0);
        grad.addColorStop(0, 'hsl('+hue+', 0%, '+(row)+'%)');
        grad.addColorStop(1, 'hsl('+hue+', 100%, '+(row/2)+'%)');
        ctx.fillStyle=grad;
        ctx.fillRect(0, row, 100, 1);
        console.log(row, row/2);
    }   
}

draw(64);

There is also a new html5 color input that works in most modern browsers: http://jsfiddle.net/4FMJM/1/

<form>
  Select  color: <input type="color" name="your-color">
  <input type="submit">
</form>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top