Unlisted
Edited
Feb 17, 2023
Insert cell
Insert cell
Insert cell
canvas = document.createElement('canvas');
Insert cell
canvas.width = 500;
Insert cell
canvas.height = 500;
Insert cell
context = canvas.getContext('2d');
Insert cell
circleRadius = 50;
Insert cell
circleFill = '#ffffff';
Insert cell
circleStroke = '#000000';
Insert cell
// Create an array to keep track of the clicked points within each circle
circlePoints = [];
Insert cell
// Function to add a small point marker to a circle at the clicked location
function addPoint(x, y) {
circlePoints.push({ x, y });
context.beginPath();
context.arc(x, y, 3, 0, 2 * Math.PI);
context.fillStyle = circleStroke;
context.fill();
}
Insert cell
// Function to remove the last point marker from a circle
function removePoint() {
circlePoints.pop();
context.clearRect(0, 0, canvas.width, canvas.height);
drawCircles();
}
Insert cell
// Function to draw circles and their associated point markers
function drawCircles() {
// Clear canvas before redrawing everything
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw circles
context.strokeStyle = circleStroke;
context.fillStyle = circleFill;
for (let i = 0; i < 5; i++) {
const x = 100 + i * 100;
const y = 100 + i * 50;
context.beginPath();
context.arc(x, y, circleRadius, 0, 2 * Math.PI);
context.stroke();
context.fill();

// Draw point markers within each circle
const points = circlePoints.filter(p => p.x === x && p.y === y);
context.fillStyle = circleStroke;
points.forEach(p => {
context.beginPath();
context.arc(p.x, p.y, 3, 0, 2 * Math.PI);
context.fill();
});
}
}
Insert cell
// Draw initial circles
drawCircles();
Insert cell
// Add click and double click event listeners to the canvas
canvas.addEventListener('click', event => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const points = circlePoints.filter(p => Math.sqrt((p.x - x) ** 2 + (p.y - y) ** 2) <= 3);
if (points.length > 0) {
removePoint();
} else {
addPoint(x, y);
}
});
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

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