WEB LAB 02 · JavaScript / SVG / Pointer Events

Small objects are attracted to the magnet. Create attractive UI with JavaScript and SVG

An interactive demo where you can collect small items by dragging a magnet. We will introduce how to calculate position, speed, and deceleration using JavaScript, and how to adjust it by moving it at hand.

It's fun to touch. You can understand by making it. A small laboratory for the web. Run it first, and if you feel like it, open the code and try changing one thing.

First, try touching it.

Drag the magnet. You can move it using the arrow keys on your keyboard.

Recipe for how to play

How magnets work

The device's "Reduce parallax effect" setting suppresses movement when displaying images.

See the code for this trick
// 磁石への方向に力を加え、摩擦で減速
const distance = Math.hypot(dx, dy);
const force = polarity * strength / Math.max(1600, distance ** 2);
vx += dx / distance * force * dt;
vy += dy / distance * force * dt;
vx *= Math.exp(-3 * dt);

Here is an excerpt showing how it works. Click here for the entire process including drawing, input operations, and stop processing.

View the entire implementation on GitHub ↗

SMALL INTERACTIONS

Small reactions make the site more fun.

Please click on the one that interests you. Here are four small experiments you can incorporate into your buttons and menus.

01 / Convey the status

You can immediately see that the switch has been made.

Tips to incorporate

Use this for an on/off setting. Update the label and aria-pressed along with the color, rather than relying on color alone.

button[aria-pressed="true"] { background: #fff0bc; }
02 / Create a comfortable pushing feeling

It sinks, bounces, and comes back.

Tips to incorporate

For a playful CTA. If you transform using transform, the position of the surrounding text will not change. Even if you hit repeatedly, the animation will not overlap.

Button demo and how to make →
03 / Create the joy of opening
open a small box

Thank you for finding me.
Even small reactions are part of the site's personality.

Take out the explanation when you need it.

Tips to incorporate

Useful for FAQs and extra details. HTML's details and summary elements open and close without JavaScript and support keyboard interaction.

How to make a drawer menu →
04 / Reply to operations

Still blank. Please give me a push.

Tips to incorporate

For feedback on successful operations, such as copy completion. This model only increases the number of marks when you press it, but does not save or send it. There can be up to 6 marks.

status.textContent = 'コピーしました';

None of these demos plays sound. Animations are skipped when your device requests reduced motion.

Try them in this order and you'll see the difference.

  1. Grab the center magnet and move it to the right or left. It is a success if the small objects gather around the magnet.
  2. Switch to repulsion and bring the magnet closer to the small object. This time, make sure that the small items are separated.
  3. Varying the strength, pull small objects from the same distance and compare.

To run it on your own computer.

The entire demo on this page is in a public repository. Below are the steps to copy and run the site. The short code snippet above won't work.

1. Check the execution environment

Open a terminal and run it line by line. Requires Git and Node.js.

git --version
node --version
npm --version

Results to check: Each command should display a version number. This project requires Node.js 22.12.0 or later. If a command is missing, use Git official and Node.js official to set up your environment.

2. Get the code and launch

Move to the folder you want to save it to, then execute the following line by line. If a folder with the same name already exists, choose a different location.

git clone https://github.com/R-Koda/ryu-koda.com.git
cd ryu-koda.com
npm ci
npm run dev -- --host 127.0.0.1 --port 4321

Results to check:Finally, the local server URL will be displayed and the terminal will remain open. If an error occurs, do not proceed and check the output of the previous command.

3. Open the experiment page

Open http://127.0.0.1:4321/playground/magnets/ in your browser. If the same demo appears and responds as described above, it is running successfully. If Terminal shows a different port, use that port instead. Press Ctrl+C in Terminal to stop the server.

Which file should I read?
  • src/components/Experiment.astro:SVG, HTML, CSS for appearance.
  • src/scripts/experiments.ts contains the experiment interactions. Look for if(kind==='magnets').
  • src/pages/playground/[slug].astro: Common layout for this explanation page.

If the screen is white, check your terminal for errors and your browser's developer tools. If the movement stops, also check the "Reduce parallax effect" setting on your device. This demo will suppress movement according to that setting.

How does it work?

Point 1

Each small object has a position x and y and a velocity vx and vy. Find the direction and distance from the difference with the magnet, and add velocity in that direction.

Point 2

Since the force increases rapidly as the distance decreases, we set a lower limit for the denominator with Math.max(1600, d*d). The deceleration for each frame is Math.exp(-3*dt).

Point 3

SVG has different display size and internal coordinates. Convert the finger position to SVG coordinates with getScreenCTM().inverse() and retain the operation while dragging with setPointerCapture.

Try changing one thing and compare.

Open src/scripts/experiments.ts in your editor and find the branch for this experiment.

What to change:In the magnets experiment's step function, change Math.exp(-3*dt) to Math.exp(-6*dt) for both the x and y directions.

Result changes:If you move the magnet with the same settings, the momentum of the small object will be weaker, making it easier to stop. Before and after the change, use "Rearrange small items" to align the initial positions and compare.

Once saved, return to your browser and reload if necessary. Make a note of the original values ​​so you can quickly go back and compare.

before incorporating it into your site.

This is an approximation for visual enjoyment. It does not reproduce the physical magnetic field, nor does it calculate collisions between small objects.

Instead of conveying information through movement alone, it can also be used with keyboard operations and settings that reduce movement. First, incorporate it into one part and make sure that it does not interfere with the readability of articles and menus.

Implementation confirmation:Full interaction source code / HTML/SVG/CSS / MDN:setPointerCapture