Skip to content

Instantly share code, notes, and snippets.

@georgebyte
Last active September 13, 2020 20:13
Show Gist options
  • Save georgebyte/5169458 to your computer and use it in GitHub Desktop.
Save georgebyte/5169458 to your computer and use it in GitHub Desktop.
jQuery: Background color picker (pick color from image by clicking on it)
var image = new Image();
image.src = "sample.jpg";
$(image).load(function() {
ctx.drawImage(image, 0, 0);
});
$(canvas).click(function(e) {
var canvasOffset = $(canvas).offset();
var canvasX = Math.floor(e.pageX-canvasOffset.left);
var canvasY = Math.floor(e.pageY-canvasOffset.top);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pixels = imageData.data;
var pixelRedIndex = ((canvasY - 1) * (imageData.width * 4)) + ((canvasX - 1) * 4);
var pixelcolor = "rgba("+pixels[pixelRedIndex]+", "+pixels[pixelRedIndex+1]+", "+pixels[pixelRedIndex+2]+", "+pixels[pixelRedIndex+3]+")";
$("body").css("backgroundColor", pixelcolor);
});
@Pixelizer
Copy link

Hi, looks nice and tiny. Can you show me a how to example to use this script? Thanx, P

@georgebyte
Copy link
Author

Sorry for such a late answer. I didn't see your comment.

Here is a sample html page, that uses this script.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            var canvas = $("#myCanvas").get(0);
            var ctx = canvas.getContext("2d");

            var image = new Image();
            image.src = "sample.jpg";
            $(image).load(function() {
                ctx.drawImage(image, 0, 0);
            });

            $(canvas).click(function(e) {
                var canvasOffset = $(canvas).offset();
                var canvasX = Math.floor(e.pageX-canvasOffset.left);
                var canvasY = Math.floor(e.pageY-canvasOffset.top);

                var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                var pixels = imageData.data;
                var pixelRedIndex = ((canvasY - 1) * (imageData.width * 4)) + ((canvasX - 1) * 4);
                var pixelcolor = "rgba("+pixels[pixelRedIndex]+", "+pixels[pixelRedIndex+1]+", "+pixels[pixelRedIndex+2]+", "+pixels[pixelRedIndex+3]+")";

                $("body").css("backgroundColor", pixelcolor);
            });
        });
    </script>
</head>
<body>
    <canvas id="myCanvas" width="500" height="500">
        Your user agent does not support the HTML5 Canvas element.
    </canvas>
</body>
</html>

@duykhoa
Copy link

duykhoa commented May 11, 2017

What is pixelRedIndex mean, and why we need to multiply with number 4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment