public
Last active

Canvas Color Picker

  • Download Gist
buildPicker.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
var app = {};
 
app.$colors = $('canvas.color-palette');
app.colorctx = app.$colors[0].getContext('2d');
 
// Build Color palette
app.buildColorPalette = function() {
var gradient = app.colorctx.createLinearGradient(0, 0, app.$colors.width(), 0);
 
// Create color gradient
gradient.addColorStop(0, "rgb(255, 0, 0)");
gradient.addColorStop(0.15, "rgb(255, 0, 255)");
gradient.addColorStop(0.33, "rgb(0, 0, 255)");
gradient.addColorStop(0.49, "rgb(0, 255, 255)");
gradient.addColorStop(0.67, "rgb(0, 255, 0)");
gradient.addColorStop(0.84, "rgb(255, 255, 0)");
gradient.addColorStop(1, "rgb(255, 0, 0)");
 
// Apply gradient to canvas
app.colorctx.fillStyle = gradient;
app.colorctx.fillRect(0, 0, app.colorctx.canvas.width, app.colorctx.canvas.height);
// Create semi transparent gradient (white -> trans. -> black)
gradient = app.colorctx.createLinearGradient(0, 0, 0, app.$colors.height());
gradient.addColorStop(0, "rgba(255, 255, 255, 1)");
gradient.addColorStop(0.5, "rgba(255, 255, 255, 0)");
gradient.addColorStop(0.5, "rgba(0, 0, 0, 0)");
gradient.addColorStop(1, "rgba(0, 0, 0, 1)");
 
// Apply gradient to canvas
app.colorctx.fillStyle = gradient;
app.colorctx.fillRect(0, 0, app.colorctx.canvas.width, app.colorctx.canvas.height);
 
app.$colors.mousedown(function(e) {
 
// Track mouse movement on the canvas if the mouse button is down
$(document).mousemove(function(e) {
app.colorEventX = e.pageX - ms.$colors.offset().left;
app.colorEventY = e.pageY - ms.$colors.offset().top;
});
// Get the color at the current mouse coordinates
app.colorTimer = setInterval(app.getColor, 50);
})
 
// On mouseup, clear the interval and unbind the mousemove event,
// it should only happen if the button is down
.mouseup(function(e) {
clearInterval(ms.colorTimer);
$(document).unbind('mousemove');
});
};
color-picker.html
HTML
1
<canvas class="color-palette" width="284" height="155"></canvas>
getColor.js
JavaScript
1 2 3 4 5 6
app.getColor = function(e) {
var newColor;
 
imageData = app.colorctx.getImageData(app.colorEventX, app.colorEventY, 1, 1);
app.selectedColor = 'rgb(' + imageData.data[4] + ', ' + imageData.data[5] + ', ' + imageData.data[6] + ')';
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.