Skip to content

Instantly share code, notes, and snippets.

@earlin
Created March 23, 2019 11:46
Show Gist options
  • Save earlin/ff734457f8fc17aaf6184386389a4b3b to your computer and use it in GitHub Desktop.
Save earlin/ff734457f8fc17aaf6184386389a4b3b to your computer and use it in GitHub Desktop.
I'm just playing with mithril until I made a pen tool :D
export const Canvas: Mithril.FactoryComponent = () => {
let canvas: HTMLCanvasElement, context: CanvasRenderingContext2D;
let points: number[] = [];
let data: ImageData;
function onMouseDown(e: MouseEvent) {
data = context.getImageData(0, 0, canvas.width, canvas.height);
points.push(e.offsetX, e.offsetY);
}
function onMouseUp(e: MouseEvent) {
points.splice(0);
}
function onMouseMove(e: MouseEvent) {
if (points.length === 0) return;
points.push(e.offsetX, e.offsetY);
context.putImageData(data, 0, 0);
context.beginPath();
for (let i = 0; i < points.length; i += 2) {
const x = points[i],
y = points[i + 1];
if (i === 0) context.moveTo(x, y);
else context.lineTo(x, y);
}
context.stroke();
}
return {
oncreate({ dom }) {
canvas = dom as HTMLCanvasElement;
context = canvas.getContext('2d');
},
view() {
return m('canvas', {
onmousedown: onMouseDown,
onmouseup: onMouseUp,
onmousemove: onMouseMove,
onmouseout: onMouseUp,
});
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment