Convert an Image to dataUri
function toDataUri(img, scalar = 1) {
const canvas = document.createElement('canvas');
canvas.width = img.width * scalar;
canvas.height = img.height * scalar;
canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL('image/png');
}
const img = new Image();
img.crossOrigin = 'Anonymous';
img.addEventListener('load', () => {
const thumb = new Image();
// use the data URI as the source
thumb.src = toDataUri(img, .3);
document.body.appendChild(thumb);
});
img.src = 'https://zevanrosser.com/fotoda/slide-shot-9.jpg';
Load an image and convert it to a data URI.
Make a Debugging Dot
function dot(x, y, radius, color) {
const el = document.createElement('div');
const size = `${radius * 2}px`;
Object.assign(el.style, {
position: 'absolute',
left: `${x}px`,
top: `${y}px`,
width: size,
height: size,
transform: `translate(${-radius}px, ${-radius}px)`,
borderRadius: '50%',
background: color
});
el.classList.add('dot');
document.body.appendChild(el);
return el;
}
dot(100, 100, 10, 'red');
dot(200, 100, 5, 'blue');
for (let i = 0; i < 20; i++) {
dot(20 + i * 12, 200, 5, `hsl(${i * 10}deg, 60%, 50%)`)
}
Draw a dot – good for visualizing things when doing animation and positioning logic.
Editible Div With Memory (localStorage)
const el = document.createElement('div')
el.innerHTML = localStorage.memory == null ? 'type here' :
localStorage.memory
el.contentEditable = true;
document.body.appendChild(el);
document.addEventListener('keyup', () => {
localStorage.memory = el.innerHTML;
});
Create an editable div that remembers what was typed in it.
createElement and Object.assign
const el = document.createElement('div');
Object.assign(el.style, {
position: 'absolute',
left: '100px',
top: '100px',
width: '30px',
height: '30px',
background: 'linear-gradient(black, red)',
transform: 'rotate(15deg)'
});
document.body.appendChild(el);
Fast and easy way to set many styles on a DOM node. Click/tap the “Try it out” button to play around with the code.