Published
Edited
Feb 8, 2019
1 fork
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
drawableCanvas = () => {
const canvas = DOM.canvas(300, 300); // Creates a canvas element
const context = canvas.getContext("2d");
let mouseDown = false;
let lastX;
let lastY;
function drawLine(x, y, lastX, lastY) {
context.strokeStyle = "#000000";
context.lineWidth = 12;
context.lineJoin = "round";

context.beginPath();
context.moveTo(lastX, lastY);
context.lineTo(x, y);
context.closePath();
context.stroke();

return [x, y];
}
function handleMousedown() {
mouseDown = true;
};
function handleMouseup() {
mouseDown = false;
[lastX, lastY] = [undefined, undefined]; // Undefined until first click
};
function handleMousemove(e) {
const rect = e.target.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;

if (mouseDown) {
[lastX, lastY] = drawLine(x, y, lastX, lastY);
}
};
// The code below is what makes the canvas "drawable" and gives it a nice black border.
canvas.addEventListener("mousedown", handleMousedown);
canvas.addEventListener("mouseup", handleMouseup);
canvas.addEventListener("mousemove", handleMousemove);
context.fillStyle = "#ffffff";
context.fillRect(0, 0, 300, 300);
return canvas;
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more