Skip to content

Instantly share code, notes, and snippets.

@malchata
Created December 3, 2020 18:51
Show Gist options
  • Save malchata/b8d742d58e10464be117b09fa9009736 to your computer and use it in GitHub Desktop.
Save malchata/b8d742d58e10464be117b09fa9009736 to your computer and use it in GitHub Desktop.
Chemistreak: a paint worklet of pseudo-random hexagonal disarray!
/* global registerPaint */
const paintName = "chemistreak";
class Chemistreak {
static get inputProperties () {
return [
`--${paintName}-tile-width`,
`--${paintName}-alternate-by`,
`--${paintName}-stroke-weight`,
`--${paintName}-stroke-color`,
`--${paintName}-probability`,
];
}
paint (ctx, geom, properties) {
const tileWidth = parseInt(properties.get(`--${paintName}-tile-width`));
const gap = parseInt(properties.get(`--${paintName}-alternate-gap`));
const probability = parseFloat(properties.get(`--${paintName}-probability`));
const halfProbability = probability / 2;
const tileHeight = (tileWidth * (7 / 6)) - (gap / 2);
const heightIncrement = tileHeight * (1 / 7);
const xTiles = geom.width / tileWidth;
const yTiles = geom.height / tileHeight;
ctx.strokeStyle = properties.get(`--${paintName}-stroke-color`).toString().trim();
ctx.lineWidth = parseFloat(properties.get(`--${paintName}-stroke-weight`));
ctx.lineCap = "round";
for (let y = 0; y < yTiles; y++) {
const yOffset = y * tileHeight;
for (let x = 0; x < xTiles; x++) {
if (Math.random() >= halfProbability) {
const xOffset = x * tileWidth;
const xMidTile = (xOffset + (tileWidth / 2)) - gap;
const xFullTile = xOffset + tileWidth;
const midTop = yOffset + (heightIncrement * 2);
const midBottom = yOffset + (heightIncrement * 5);
const coords = [
[xMidTile , yOffset ], // Top middle
[xFullTile, midTop ], // Right top
[xFullTile, midBottom ], // Right bottom
[xMidTile , yOffset + tileHeight], // Bottom middle
[xOffset , midBottom ], // Left bottom
[xOffset , midTop ] // Left top
];
// 1. Top middle
if (Math.random() >= probability) {
ctx.moveTo(coords[0][0] , coords[0][1]);
ctx.lineTo(coords[1][0] , coords[1][1]);
ctx.stroke();
}
// 2. Right top
if (Math.random() >= probability) {
ctx.moveTo(coords[1][0] , coords[1][1]);
ctx.lineTo(coords[2][0] , coords[2][1]);
ctx.stroke();
}
// 3. Right bottom
if (Math.random() >= probability) {
ctx.moveTo(coords[2][0] , coords[2][1]);
ctx.lineTo(coords[3][0] , coords[3][1]);
ctx.stroke();
}
// 4. Bottom middle
if (Math.random() >= probability) {
ctx.moveTo(coords[3][0] , coords[3][1]);
ctx.lineTo(coords[4][0] , coords[4][1]);
ctx.stroke();
}
// 5. Left bottom
if (Math.random() >= probability) {
ctx.moveTo(coords[4][0] , coords[4][1]);
ctx.lineTo(coords[5][0] , coords[5][1]);
ctx.stroke();
}
// 5. Left top
if (Math.random() >= probability) {
ctx.moveTo(coords[5][0] , coords[5][1]);
ctx.lineTo(coords[0][0] , coords[0][1]);
ctx.stroke();
}
}
}
}
}
}
registerPaint(paintName, Chemistreak);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment