Get background color of input range position

I have an input with a range type that has a background color that is a gradient. I would like the background color of the gradient to be output to the class where the range value is currently located.

For example, if the input range is between 1-100, and the input value is 1, then this will be the left side of the input, the color will be displayed to the left.

enter image description here

Any help in this matter would be greatly appreciated.

+4
source share
1 answer

You can draw your gradient on the canvas and use getImageDatato get the selected pixel color.

A Demo: http://jsfiddle.net/m1erickson/YaQ6J/

:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
    #myRange{width:300px;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    ctx.font="14px verdana";

    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    var x1=0;
    var y1=10;
    var x2=canvas.width;
    var y2=10;

    // create a gradient
    var gradient=ctx.createLinearGradient(x1,y1,x2,y2);
    gradient.addColorStop(0.00,"indigo");
    gradient.addColorStop(1.00,"steelblue");

    // draw the gradient across the canvas
    ctx.fillStyle=gradient;
    ctx.fillRect(x1,y1-10,x2-x1,20);

    // get the pixel color array for the gradient
    var data=ctx.getImageData(x1,y1,canvas.width,1).data;

    // get the gradient using a range control
    $("#myRange").on("input change",function(){
        var value=$(this).val();
        var i=value*4;
        var r=data[i];
        var g=data[i+1];
        var b=data[i+2];
        var a=data[i+3];

        // change the result rectangle to the mouseX color
        var fill="rgba("+r+","+g+","+b+","+a+")";
        ctx.fillStyle=fill;
        ctx.clearRect(0,20,canvas.width,30);
        ctx.fillRect(0,25,50,20);
        ctx.fillText(fill,75,40);
    });

}); // end $(function(){});
</script>
</head>
<body>
    <input id="myRange" type="range" min="0" max="299"><br>   
    <canvas id="canvas" width=300 height=45></canvas>
</body>
</html>
+6

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


All Articles