HTML 5 Canvas: Loaded Image Color Picker

I am creating an application using html canvas and javascript. You download and select an image and a color, but I have a problem where I can only pick colors from a small part of the loaded image. I've tried a few things to fix this and I'm a bit stumped. Does anyone have any idea? I used this to help me: http://www.webdesignerdepot.com/2013/03/how-to-create-a-color-picker-with-html5-canvas/

<canvas width="600" height="300" id="canvas_picker"></canvas>
<div id="hex">HEX: <input type="text"></input></div>
<div id="rgb">RGB: <input type="text"></input></div>

      

var $files = document.getElementById('file_upload').files[0];
var reader = new FileReader();
reader.onload = imageIsLoaded;

function imageIsLoaded(e) {
    // canvas
    var canvas = document.getElementById('canvas_picker');
    var context = canvas.getContext('2d');
    var $img = $('<img>', { src: e.target.result });

    // Draws Image
    $img.load(function() {
        context.drawImage(this,10, 10);
        $("#loader").hide();
    }); 
}

$('#canvas_picker').click(function(event){
    // getting user coordinates
    var x = event.pageX;
    var y = event.pageY;

    // getting image data and RGB values
    var img_data = canvas.getImageData(x,y , 1, 1).data;
    var R = img_data[0];
    var G = img_data[1];
    var B = img_data[2]; 
    var rgb = R + ',' + G + ',' + B;
    // convert RGB to HEX
    var hex = rgbToHex(R,G,B);
    // making the color the value of the input
    console.log(R);
    console.log(B);
    console.log(G);

    $('#rgb input').val(rgb);
    console.log(rgb);
    $('#hex input').val('#' + hex);
});

function rgbToHex(R, G, B) {
    return toHex(R) + toHex(G) + toHex(B)
}

function toHex(n) {
    n = parseInt(n, 10);
    if (isNaN(n)) 
        return "00";

    n = Math.max(0, Math.min(n, 255));
    return "0123456789ABCDEF".charAt((n - n % 16) / 16)  + "0123456789ABCDEF".charAt(n % 16);
}
reader.readAsDataURL($files);

      

when i click on a pixel outside of a small area it returns as 0.

+3


source to share


2 answers


jsBin demo

Fixed some issues such as getImageData

trying to read canvas

instead context

and the image was drawn at XY 10.10 instead of 0.0.
Also, you may want to adjust the canvas size to the loaded W / H image.

To prevent the coordinates from being miscalculated (because you get the click coordinate that matches the edges of the page), and to get the exact position of the mouse inside the canvas , you may need to subtract the canvas offset to the left / top from the resulting coordinate x

.y



var $picked = $("#picked"); // Just to preview picked colors
var canvas = $('#canvas_picker')[0];
var context = canvas.getContext('2d');


$("#file_upload").change(function (e) {
  var F = this.files[0];
  var reader = new FileReader();
  reader.onload = imageIsLoaded;
  reader.readAsDataURL(F);  
});

function imageIsLoaded(e) {
  var img = new Image();
  img.onload = function(){
    canvas.width  = this.width;    // If needed? adjust canvas size
    canvas.height = this.height;   // respective to image size
    context.drawImage(this, 0, 0); // Draw image at 0, 0, not at 10, 10
  };
  img.src = e.target.result;
}

$('#canvas_picker').click(function(event){
  var x = event.pageX - $(this).offset().left; // Fixed coordinates
  var y = event.pageY - $(this).offset().top; // respective to canvas offs.
  var img_data = context.getImageData(x,y , 1, 1).data;
  var R = img_data[0];
  var G = img_data[1];
  var B = img_data[2]; 
  var rgb = R + ',' + G + ',' + B ;
  var hex = rgbToHex(R,G,B);
  $('#rgb input').val( rgb );
  $('#hex input').val('#' + hex);
  $picked.append("<span style='background:#"+hex+"'>#"+hex+"</span>");
});

function rgbToHex(R, G, B) {
  return toHex(R) + toHex(G) + toHex(B);
}

function toHex(n) {
  n = parseInt(n, 10);
  if (isNaN(n))  return "00";
  n = Math.max(0, Math.min(n, 255));
  return "0123456789ABCDEF".charAt((n - n % 16) / 16)  + "0123456789ABCDEF".charAt(n % 16);
}
      

*{margin:0;}
canvas{background:#ddd;}
#picked span{
  display:inline-block;
  width:50px;
  height:50px;
  margin:3px;
  text-align:center;
  text-shadow:1px 1px 1px #000;
  font:8px/50px Arial;
  color:#fff;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas width="600" height="300" id="canvas_picker"></canvas><br>
<input type="file" id="file_upload"><br>
<div id="hex">HEX: <input type="text"></div>
<div id="rgb">RGB: <input type="text"></div>

<div id="picked"></div>
      

Run code


0


source


When I try to step through the code, it works fine, except that the mouse is not well aligned with the picker. This is because you are rendering the image at coordinate (10,10), but you land on the mouse pos (x, y).

// I replaced the following code
var $img = $('<img>', { src: e.target.result });
$img.load(function() {
    context.drawImage(this,10, 10);
    $("#loader").hide();
}); 
// By this one
var img = new Image();
$img.load(function() {
    context.drawImage(this,10, 10);
    $("#loader").hide();
}); 
img.src = e.target.result;

      



To avoid creating an HTML element that is not actually used. I also set the canvas_picker click event setting to DOM Ready, but I think this is not a problem. I also fixed the canvas issue in the click function.

// getting image data and RGB values
var canvas = document.getElementById('canvas_picker');
var context = canvas.getContext('2d');
var img_data = context.getImageData(x,y , 1, 1).data;

      

0


source







All Articles