Export Code
index.js
import { select, pointer } from 'd3';

export const main = (container, { state, setState }) => {
const width = container.clientWidth;
const height = container.clientHeight;

// Initialize middle position and blue color.
if (state.x === undefined) {
const initialState = {
x: width / 2,
y: height / 2,
color: '#0000FF
Alt + Click on a hex color
Open a color picker to modify the color
',
};
setState(() => initialState);
return;
}

// Render the SVG.
const svg = select(container)
.selectAll('svg')
.data([null])
.join('svg')
.attr('width', width)
.attr('height', height)
.style('background', '#F0FFF4
Alt + Click on a hex color
Open a color picker to modify the color
');

// Update state.x and state.y when the mouse moves.
svg.on('mousemove', (event) => {
const [x, y] = pointer(event);
setState((state) => ({ ...state, x, y }));
});

svg.on('click', () => {
setState((state) => ({
...state,
color:

Mouse Follower

Curran Kelleher

Last edited May 12, 2024
Created on Feb 06, 2024
Forked from Circles with D3

A program that follows the mouse around and changes its color using immutable update patterns.

Challenge

  • Use this pattern to make something else respond to mouse events
MIT Licensed