CSS Color Picker Gradient
const col = document.body.appendChild(
document.createElement('div')
);
Object.assign(col.style, {
position: 'absolute',
left: 0, top: 0,
width: '100%',
height: '200px',
background: 'linear-gradient(90deg, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)'
});
CSS gradient that cycles hue – useful for a colorpicker. This is the main part of the snippet:
linear-gradient(90deg, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)
Easy Hex Color Invert
let color = 0xFFFF00;
function toHexString(col) {
return '#' + ('000000' + col.toString(16)).substr(-6);
}
function onClick() {
// invert the color
color ^= 0xFFFFFF;
document.body.style.background = toHexString(color);
}
onClick();
document.addEventListener('click', onClick);
console.log('try a different initial color');
console.log('click anywhere to invert background...');
Easily invert a hex color. Expanding on yesterdays post – just one of many reasons you may want to work with colors in their integer form.
Integers to Colors
function toHexString(col) {
return '#' + ('000000' + col.toString(16)).substr(-6);
}
document.body.style.background = toHexString(0x275ba1);
console.log("#275ba1 as an integer:", 0x275ba1);
console.log("#ff0000 as an integer:", 0xff0000);
Convert an integer in hex (like 0xff0000
) to a usable hex string "#ff0000"
.
Complementary HSL
const a = document.body.appendChild(document.createElement('div')),
b = document.body.appendChild(document.createElement('div'));
let degA = degB = 0;
const size = {
width: '100px',
height: '100px'
};
Object.assign(a.style, size);
Object.assign(b.style, size);
function loop() {
degA += 1;
degB = degA + 180;
a.style.background = `hsl(${degA}deg, 100%, 50%)`;
b.style.background = `hsl(${degB}deg, 100%, 50%)`;
requestAnimationFrame(loop);
}
loop();
In HSL a hue difference of 180 degrees between two values will create a set of complimentary colors.
Canvas ImageData
const canvas = document.body.appendChild(
document.createElement('canvas')
);
const width = 200;
canvas.width = canvas.height = width;
const c = canvas.getContext('2d');
const pixels = c.createImageData(canvas.width, canvas.height);
const size = canvas.width * canvas.height;
let index = 0, x, y;
for (var i = 0; i < size; i++){
x = i % width;
y = Math.floor(i / width);
pixels.data[index++] = x;
pixels.data[index++] = y;
pixels.data[index++] = width - x;
pixels.data[index++] = 255;
}
c.putImageData(pixels, 0, 0);
This shows how to set pixel data on an html5 canvas.