Array Sum Golfed
a = [1, 2, 3, 6, 9];
sum = eval(a.join`+`);
console.log(sum);
Found myself doing something like this a few times… easy golfed array sum. I saw this over at codegolf stackexchange here.
That whole thread is a great. I plan to post more from there in the future.
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.
isPointInPath Canvas
const canvas = document.createElement('canvas');
const c = canvas.getContext('2d');
let mouseX = 0, mouseY = 0;
canvas.width = 400;
canvas.height = 400;
document.body.appendChild(canvas);
document.body.style.margin = 0;
c.fillStyle = 'black';
c.fillRect(0, 0, canvas.width, canvas.height);
document.addEventListener('mousemove', e => {
mouseX = e.clientX;
mouseY = e.clientY;
});
// no scroll on mobile:
document.addEventListener('touchmove',
e => e.preventDefault(), { passive: false });
document.addEventListener('touchmove', e => {
mouseX = e.touches[0].clientX;
mouseY = e.touches[0].clientY;
});
const loop = () => {
c.fillStyle = 'black';
c.fillRect(0, 0, canvas.width, canvas.height);
c.lineWidth = 3;
c.strokeStyle = 'blue';
c.beginPath();
c.moveTo(20, 20);
c.lineTo(110, 20);
c.lineTo(110, 110);
c.lineTo(20, 110);
c.closePath();
if (c.isPointInPath(mouseX, mouseY)) {
c.strokeStyle = 'white';
c.fillStyle = 'red';
c.fill();
}
c.stroke();
requestAnimationFrame(loop);
};
loop();
See if a point is with a path inside canvas. Take a look at MDN for more info.
Short Floor (to Integer)
console.log(~~6.62606889);
console.log(0|6.62606889);
console.log(0^6.62606889);
console.log(Math.floor(6.62606889));
console.log(parseInt(6.62606889,10));
A few different ways to get rid of decimal values… turning a float into an int.
Make a Grid
const cellSize = 25;
const cols = 10;
const rows = 20;
function makeDot(x, y) {
const dot = document.body.appendChild(
document.createElement('div')
);
dot.classList.add('cell');
Object.assign(dot.style, {
position: 'absolute',
left: `${x}px`,
top: `${y}px`,
width: `${cellSize}px`,
height: `${cellSize}px`,
outline: '1px solid black',
cursor: 'pointer',
background: 'gray'
});
return dot;
}
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
makeDot(x * cellSize, y * cellSize);
}
}
// make a cell red when it is rolled over
document.addEventListener('mouseover', e => {
if (e.target.classList.contains('cell')) {
e.target.style.background = 'red';
}
});
Here is a simple example for arranging divs in a grid.