Print a Tabula Recta (codegolf)
const tabulaRecta = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.replace(/./g,"$&$'$`\n");
const pre = document.createElement('pre');
document.body.appendChild(pre);
pre.innerHTML = tabulaRecta;
// technique comes from https://codegolf.stackexchange.com/a/87035/63485
This snippet comes from the
the codegolf stackexchange. A little while back a challenge for printing a tabula recta popped up along with a very nice answer from user Neil. Take a look at the answer here.
Shuffle an Array
const nums = [1, 10, 20, 30, 50, 88];
nums.sort(() => Math.random() - 0.5);
console.log(nums);
Common way to shuffle the values in an array.
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.
Draw a Spiral with Resize
const canvas = document.body.appendChild(
document.createElement('canvas')
);
const c = canvas.getContext('2d');
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw();
}
function draw() {
c.clearRect(0, 0, canvas.width, canvas.height);
c.fillStyle = 'blue';
const iter = 300,
halfWidth = window.innerWidth / 2,
halfHeight = window.innerHeight / 2;
let rad = 0, theta = 0, x, y;
for (let i = 0; i < iter; i++) {
x = halfWidth + rad * Math.cos(theta);
y = halfHeight + rad * Math.sin(theta);
c.fillRect(x, y, 5, 5);
rad += Math.min(window.innerWidth, window.innerHeight) * 0.0015;
theta += .1;
}
}
resize();
window.addEventListener('resize', resize);
Expanding on yesterdays post, this draws a resizable sprial on a canvas.