Public
Edited
Apr 25
2 forks
Insert cell
Insert cell
Insert cell
Insert cell
canvasElement = html`<canvas id="scatterplot" width="600" height="300" style="background-color: #002036;"></canvas>`
Insert cell
Insert cell
Insert cell
canvas = canvasElement
Insert cell
Insert cell
numberOfPoints = 100
Insert cell
// // optional: make dynamic attributes
// viewof numberOfPoints = Inputs.range([100, 10000], {label: "number of points", step: 10, value: 100})
Insert cell
Insert cell
Insert cell
Insert cell
{
// apply the '2D' Canvas context to the canvas element (as opposed to WebGL)
const ctx = canvas.getContext('2d')

// clear any existing points before drawing new ones
ctx.clearRect(0, 0, canvas.width, canvas.height)

// use a for loop to draw the dots at random x and y positions
for (let i = 0; i < numberOfPoints; i++) {
let x = Math.random() * canvas.width
let y = Math.random() * canvas.height

ctx.beginPath();
ctx.arc(x, y, sizeOfPoints / 2, 0, 2 * Math.PI) //x-center, y-center, radius, start angle, end angle
ctx.fillStyle = pointColor
ctx.fill()
ctx.closePath() // close the circle
}

return canvas
}
Insert cell
// If you want to run from a .html file

// <!DOCTYPE html>
// <html lang="en">
// <head>
// <meta charset="UTF-8">
// <meta name="viewport" content="width=device-width, initial-scale=1.0">

// <title>Canvas Scatterplot</title>
// </head>
// <body>
// <!-- Create the HTML canvas element -->
// <canvas id="scatterplot" width="600" height="300"></canvas>

// <script>
// // Grab the canvas
// const canvas = document.getElementById('scatterplot')
// canvas.style.backgroundColor = '#002036'

// // Apply the '2d' context (as opposed to 'webgl')
// const ctx = canvas.getContext('2d')

// // Define the visualization's attributes
// let numberOfPoints = 100
// let sizeOfPoints = 10
// let pointColor = 'white'

// // Clear the canvas (in case any points have already been drawn)
// ctx.clearRect(0, 0, canvas.width, canvas.height)

// // Use a for loop to draw all the points
// for (let i = 0; i < numberOfPoints; i++) {
// let x = Math.random() * canvas.width
// let y = Math.random() * canvas.height

// ctx.beginPath()
// ctx.arc(x, y, sizeOfPoints / 2, 0, 2 * Math.PI) //x-center, y-center, radius, start angle, end angle
// ctx.fillStyle = pointColor
// ctx.fill()
// ctx.closePath() // close the circle
// }
// </script>
// </body>
// </html>


// <!--
// Challenge 1: Make dynamic attributes: radius, number of dots, color of dots, color of background
// Challenge 2: Animate the dots, color of dots, color of background
// -->

// <!--
// Notes:
// - Coordinates are (0, 0) at the top left corner of the canvas
// -->
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