Published
Edited
Mar 22, 2018
6 stars
Insert cell
Insert cell
html`<div id="myElement">
Paint worklets
</div>

<style>
#myElement {
text-align: center;
padding: 200px 50px;
color: #fff;
font-size: 5rem;
font-family: futura, sans-serif;
font-weight: bold;
--circle-color: red;
background-image: paint(${workletName});
}
</style>`
Insert cell
Insert cell
class WorkletPainter {
paint(ctx, geom, properties) {
const size = 32;
for(let y = 0; y < geom.height/size; y++) {
for(let x = 0; x < geom.width/size; x++) {
const color = `rgb(${~~(Math.random() * 240)}, 150, 200)`;
ctx.beginPath();
ctx.fillStyle = color;
ctx.rect(x * size, y * size, size, size);
ctx.fill();
}
}
}
}
Insert cell
Insert cell
workletName = `worklet-${await sha256(WorkletPainter.toString())}`
Insert cell
Insert cell
worklet = `registerPaint('${workletName}', ${WorkletPainter.toString()})`
Insert cell
Insert cell
workletBlob = URL.createObjectURL(new Blob([worklet], { type: 'application/javascript' }))
Insert cell
Insert cell
window.CSS.paintWorklet.addModule(workletBlob)
Insert cell
Insert cell
function sha256(str) {
// We transform the string into an arraybuffer.
var buffer = new TextEncoder("utf-8").encode(str);
return crypto.subtle.digest("SHA-256", buffer).then(function (hash) {
return hex(hash);
});
}

Insert cell
function hex(buffer) {
var hexCodes = [];
var view = new DataView(buffer);
for (var i = 0; i < view.byteLength; i += 4) {
// Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
var value = view.getUint32(i)
// toString(16) will give the hex representation of the number without padding
var stringValue = value.toString(16)
// We use concatenation and slice for padding
var padding = '00000000'
var paddedValue = (padding + stringValue).slice(-padding.length)
hexCodes.push(paddedValue);
}

// Join all the hex strings into one
return hexCodes.join("");
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more