Transparent HTML5 canvas overlay gradients

I am creating a color picker in HTML5 as the gradient below

Color gradient

It consists of three elements:

  • Solid red background color (must be changed)
  • Black and transparent gradient from bottom to top
  • White - transparent gradient from left to right

I managed to create a single gradient and one color, but I can’t figure out how to apply a solid color and two gradients together. How can i do this?

(I could provide my code, but it is quite general and would not be useful)

+4
source share
2 answers

You can superimpose two gradients on top of each other:

Demo screenshot

Horizontal gradient

( HUE), 100% 50% - :

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

.

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

, :

Hue palette

demo, . , - , .

, .

+8

, "" , . , .

jsfiddle . - , , :

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);

html5, : http://jsfiddle.net/4FMJM/1/

<form>
  Select  color: <input type="color" name="your-color">
  <input type="submit">
</form>
0

Source: https://habr.com/ru/post/1526872/


All Articles