JSFiddle - React, Tailwind, and code Playground
by Travis Almand
HTML
<p>Pick a color, any color...</p>
<input type="color" id="color" value="#307B21" />
<br /><br />
<canvas id="canvas" width="500" height="150"></canvas>
<p>Output:</p>
<div id="output"></div>
JavaScript
const color = document.getElementById('color');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let pickedColors = {};
function getColor (imageData) {
return `rgba(${imageData.data[0]}, ${imageData.data[1]}, ${imageData.data[2]}, ${imageData.data[3]})`;
}
function setColor (event) {
let color = event ? event.target.value : '#307B21';
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'color';
// grays
ctx.fillStyle = '#333333';
ctx.fillRect(0, 50, 100, 100);
ctx.fillStyle = '#707070';
ctx.fillRect(100, 50, 100, 100);
ctx.fillStyle = '#C5C5C5';
ctx.fillRect(200, 50, 100, 100);
ctx.fillStyle = '#E0E0E0';
ctx.fillRect(300, 50, 100, 100);
ctx.fillStyle = '#F5F5F5';
ctx.fillRect(400, 50, 100, 100);
// color
ctx.fillStyle = color;
ctx.fillRect(0, 0, 500, 100);
pickedColors = {
a: getColor(ctx.getImageData(50, 75, 1, 1)),
b: getColor(ctx.getImageData(150, 75, 1, 1)),
c: getColor(ctx.getImageData(250, 75, 1, 1)),
d: getColor(ctx.getImageData(350, 75, 1, 1)),
e: getColor(ctx.getImageData(450, 75, 1, 1))
};
document.getElementById('output').innerText = `a: ${pickedColors.a}
b: ${pickedColors.b}
c: ${pickedColors.c}
d: ${pickedColors.d}
e: ${pickedColors.e}`;
}
color.addEventListener('change', setColor);
setColor();