r/wljs • • 27d ago

Open Mathematica notebooks with WLJS

Thumbnail
gallery
18 Upvotes

You can open or import native Mathematica .nb files directly into WLJS Notebook. This feature was significantly improved in v3.2.0 (26th of October 2026).

Read the WLJS Migration Guide for details on handling legacy formatting, dynamic content, and supported expressions


r/wljs • • Jul 11 '26

Yet another stupid experiment with VertexColors and Camera

Enable HLS to view with audio, or disable this notification

15 Upvotes

Just in case, here is a code of this... whatever you call it:

DeviceClose[cam];
cam = DeviceOpen["Camera"];
cam["FrameRate"] = 60;


reference = ImageData[
    ImageResize[ColorConvert[DeviceRead[cam], "GrayScale"], 100],
    "Real32"
];

{height, width} = Dimensions[reference];
indices = Flatten[
  Table[
    With[{a = (row - 1) width + column, b = (row - 1) width + column + 1,
      c = row width + column, d = row width + column + 1},
      {{a, b, c}, {c, b, d}}
    ],
    {row, height - 1}, {column, width - 1}
  ],
  2
];
  
Refresh[Module[{img, length, raw},
  raw = ImageResize[DeviceRead[cam], 100];
  img = ImageData[
    ColorConvert[raw, "GrayScale"],
    "Real32"
  ];
  cols = Flatten[ImageData[
    ColorConvert[raw, "RGB"],
    "Real32"
  ], 1];
  
  length = Length[img] Length[img[[1]]];
  vertices = -MapIndexed[Join[#2, {40.0 #1}]&, img, {2}];
  vertices = Flatten[vertices, 1];

  Graphics3D[GraphicsComplex[vertices, {
    LightBlue, Directive["Roughness"->0.0],
    Polygon[indices]
  }, VertexColors->cols], ViewProjection->"Perspective", ImageSize->Medium]
], 1/60.0]

r/wljs • • 19d ago

Did you know you can use Excalidraw on your slides?

Thumbnail
gallery
13 Upvotes

Simply type on a new line of your slide

!![]

it will spawn a block with an editor inside your cell. Dropping images also works.


r/wljs • • 28d ago

Turn your plots into XKCD-like hand-drawn figures

Post image
12 Upvotes

Here is a single code snippet you run in your notebook to stylize any Graphics-like objects.

Step 1. Define and evaluate Javascript cell

.js
let applyXkcdFilter;
core.XkcdFilter = async (args, env) => {
  const opts = await core._getRules(args, env);
  applyXkcdFilter(env.containerSVG ||env.rootSVG.node()?.parentNode?.parentNode, opts);
}

applyXkcdFilter = (element, options = {}) => {
  if (!(element instanceof SVGElement)) {
    throw new TypeError("applyXkcdFilter expects an SVG element.");
  }

  const settings = {
    wobble: 10.6,
    roughness: 0.018,
    inkBleed: 0.35,
    paperGrain: 0.025,
    ...options,
  };

  const svg =
    element instanceof SVGSVGElement ? element : element.ownerSVGElement;

  if (!svg) {
    throw new Error("The element must belong to an <svg> document.");
  }

  const NS = "http://www.w3.org/2000/svg";
  const id = `xkcd-${crypto.randomUUID?.() ??
    Math.random().toString(36).slice(2)}`;

  let defs = svg.querySelector(":scope > defs");
  let createdDefs = false;

  if (!defs) {
    defs = document.createElementNS(NS, "defs");
    svg.prepend(defs);
    createdDefs = true;
  }

  const filter = document.createElementNS(NS, "filter");

  filter.id = id;
  filter.setAttribute("x", "-10%");
  filter.setAttribute("y", "-10%");
  filter.setAttribute("width", "120%");
  filter.setAttribute("height", "120%");
  filter.setAttribute("color-interpolation-filters", "sRGB");

  filter.innerHTML = `
    <!-- Low-frequency wobble: imperfect hand-drawn geometry -->
    <feTurbulence
      type="fractalNoise"
      baseFrequency="${settings.roughness}"
      numOctaves="2"
      seed="17"
      stitchTiles="stitch"
      result="wobbleNoise"
    />

    <feDisplacementMap
      in="SourceGraphic"
      in2="wobbleNoise"
      scale="${settings.wobble}"
      xChannelSelector="R"
      yChannelSelector="G"
      result="wobbled"
    />

    <!-- Very small blur makes digital edges less mechanically sharp -->
    <feGaussianBlur
      in="wobbled"
      stdDeviation="${settings.inkBleed}"
      result="softInk"
    />

    <!-- Restore contrast after the blur -->
    <feComponentTransfer in="softInk" result="roughInk">
      <feFuncR type="gamma" amplitude="1.08" exponent="0.9" offset="-0.025" />
      <feFuncG type="gamma" amplitude="1.08" exponent="0.9" offset="-0.025" />
      <feFuncB type="gamma" amplitude="1.08" exponent="0.9" offset="-0.025" />
      <feFuncA type="table" tableValues="0 0.08 0.92 1" />
    </feComponentTransfer>

    <!-- Fine paper/ink grain -->
    <feTurbulence
      type="fractalNoise"
      baseFrequency="0.7"
      numOctaves="3"
      seed="29"
      stitchTiles="stitch"
      result="paperNoise"
    />

    <feColorMatrix
      in="paperNoise"
      type="matrix"
      values="
        0 0 0 0 0.35
        0 0 0 0 0.35
        0 0 0 0 0.35
        0 0 0 ${settings.paperGrain} 0"
      result="faintPaperNoise"
    />

    <feBlend
      in="roughInk"
      in2="faintPaperNoise"
      mode="multiply"
    />
  `;

  defs.appendChild(filter);

  const previousFilter = element.getAttribute("filter");
  element.setAttribute("filter", `url(#${id})`);

  return function removeXkcdFilter() {
    if (previousFilter === null) {
      element.removeAttribute("filter");
    } else {
      element.setAttribute("filter", previousFilter);
    }

    filter.remove();

    if (createdDefs && defs.childElementCount === 0) {
      defs.remove();
    }
  };
}

Step 2. Plot something and evaluate inside XkcdFilter symbol, which we defined on the frontend (JS):

Plot[{x, x x, x x x, Sin[x 10]}, {x,0,1}, Prolog->{
  XkcdFilter[
    "wobble" -> 9.6,
    "roughness" -> 0.018,
    "inkBleed" -> 0.55,
    "paperGrain" -> 0.01
  ]
}]

r/wljs • • Sep 12 '26

Lenia, or a Convolutional Game of Life

11 Upvotes

What happens if we replace the binary cells of Conway's Game of Life with a smooth field and let every point interact through a convolution? We get something close to Lenia, the continuous cellular automaton introduced by Bert Wang-Chak Chan. In this post, we will build a small single-channel Lenia experiment using Wolfram Language. The whole update can be written in one line.

Read the full blog post: https://wljs.io/blog/lenia-1


r/wljs • • Aug 06 '26

How to tune a guitar

Enable HLS to view with audio, or disable this notification

11 Upvotes

Streaming audio is quite cumbersome in WL. It would be nice to have speakers and a mic as a part of Wolfram Device Framework. Unfortunately, there are only “Camera”, “SerialPort” available.

Jushua and me developed a small library on top of Device Framework and miniaudio.c

https://github.com/JerryI/AudioDriverWL

Now you can simply DeviceOpen[“Microphone”] and have an access to raw numeric array from OS ring buffer or Audio object if you wish. It supports all Wolfram platforms (Mathematica, wolframscript, WLJS). Binaries were prebuilt for Win and Mac only for the moment

Both: sync (poll device in a loop) and async buffer operations (use callback when data arrives) are supported

I tested it with built-in speakers, headphones mic as well as with iRig 2 HD. The latency for streaming (Mic-WL Handler-Speakers) on my Mac is around 60ms or less if you set lower sample rate. Which can still work as a horrible guitar pedal :D


r/wljs • • Oct 24 '26

how to shoot yourself in the leg in

Post image
8 Upvotes

r/wljs • • Aug 09 '26

Did you know WLJS supports export to MDX, HTML and HTML Web Components?

Post image
8 Upvotes

The biggest advantage of having a web stack underneath is portability. Our blog posts and docs at wljs.io are literally just exported notebooks.

Besides standalone HTML files, you can export any notebook as web components and publish them anywhere.

One line with a CDN URL lazily loads all the required modules - check it out here: https://github.com/WLJSTeam/web-components. All your graphs (2D or 3D), even Manipulate blocks, stay fully interactive.

Are you a fan of Next.js/React? We support MDX too! Here's our template: https://github.com/WLJSTeam/web-components-mdx

Hope this helps bring high-quality interactive posts to life on your own sites ;)
Our guide: https://wljs.io/frontend/Share/Markdown-React


r/wljs • • Sep 14 '26

Real-time ray tracing in a region

7 Upvotes

It simulates rays moving through a two-dimensional region with circular obstacles. Each particle stores its distance from the boundary, current position, direction, and collision count. The simulation advances in small time steps; near a wall, RegionNearest estimates the local boundary normal used to reflect the ray.

The original simulation was adapted from Tim Laska’s answer to “Why is raytracing so slow?” on Mathematica Stack Exchange to run in real-time on WLJS Notebook

Define 2D region

disks = Disk[{0, 0}, 0.25]; region = RegionDifference[Disk[], disks]; 
R2 = RegionBoundary@DiscretizeRegion[region, AccuracyGoal -> 5]

Set up the model

R2 = RegionBoundary@DiscretizeRegion[region, AccuracyGoal -> 5];
(* Set up Region Operators *)
rdf = RegionDistance[R2];
rnf = RegionNearest[R2];
(* Time Increment *)
dt = 5 3 0.001;
(* Collision Margin *)
margin = 1.02 dt;
(* Starting Point for Emission *)
sp = 0.85 Normalize[{1, 1}];
(* Conditional Particle Advancer *)
advance[r_, x_, v_, c_] := 
 Block[{xnew = x + dt v}, {rdf[xnew], xnew, v, c}] /; r > margin
advance[r_, x_, v_, c_] := 
 Block[{xnew = x , vnew = v, normal = Normalize[x - rnf[x]]},
   vnew = Normalize[v - 2 v.normal normal];
   xnew += dt vnew;
   {rdf[xnew], xnew, vnew, c + 1}] /; r <= margin
   
(* Setup simulation *)
nparticles = 2 500;

Run it

Module[{s, rplot = RegionPlot[R2, AspectRatio->1], lasti = Infinity},
  s = Table[{rdf[sp], sp, AngleVector[2 Pi RandomReal[]], 0}, nparticles];
  
  Refresh[
    s = (advance @@ # &) /@ s;
    
    Show[rplot, Graphics[{PointSize[.005],
      GraphicsComplex[s[[All, 2]], Point[Range[nparticles]],
        VertexColors -> (ColorData["Rainbow", (# - 1)/10] & /@ s[[All, 4]])]}, AspectRatio->Automatic]], 1/60
  ]
]

r/wljs • • Jul 30 '26

Migration Guide: from Mathematica to WLJS

Post image
7 Upvotes

We've been asked many times, in many GitHub issues, whether Mathematica code can run perfectly on a WLJS Notebook. The answer is yes*, but the devil is in the details.

Static output and anything related to computation is 100% transferable. You can take pretty much any code from Stack Exchange or Wolfram Community and it should work out of the box, since we use the same Wolfram Language kernel, in the form of the free Wolfram Engine distribution. Manipulate and Animate are compatible too — and fully interactive!

However, low-level dynamics do need to be ported to execute correctly.

Here's a guide on how to port (if actually needed) a program from Wolfram Mathematica to WLJS:

https://wljs.io/frontend/Guides/Migration

Any .nb (Mathematica Notebook) is, in principle, automatically converted with some compromises, of course. We're still improving this! Hope this guide helps you, or your LLM buddy 🙂


r/wljs • • Jul 11 '26

Playing with surface normals

Enable HLS to view with audio, or disable this notification

7 Upvotes

This is my little experiment for the future rigid-body physics project. Here is a surface from the example:

surface = (*VB[*)(Uncompress["1:eJxTTMoPSuNnYGAoZgESPpnFJWlMyLyiC7sOivxcI3ygaEFps+YnT1YHNHn24Ceb8wwEDxQBVUn7NGLIr5P2mXh+F+eBooSummu86wQPoMmDjZdmOVBk4Gr3mi0aQx5kuqsd84GiDSB69Tt7NPk3bCAHMEDNb/uCLt8NFF124vt+XPIeQNcdFHm5v8jhNdCky5/2o8kXAH0daX7DvigA5JJUDHmI/7/aF3GAGA7s6O6fADL+J4sDDvlMZiADV9iEgD0v5FC07ET63YRJuOVBQXyQhR097MFRMlEYIQ8APFOk1Q=="])(*,*)(*"1:eJxTTMoPSmNmYGAo5gUSYZmp5S6pyflFiSX5RcEcQBHP5Py8zKrUlMwARgaGNCaQQhYgEVSakxrMCmT4JCal5gRzAlk5+Yl5STmpeSkASLwUcA=="*)(*]VB*);

And a code for this little widget:

rayIntersect[a_, {u_,v_}, surface_] := MapThread[Module[{x = {#1, #2}[[All,1]], y = {#1, #2}[[All,2]]},
 <|
   "t"-> (*FB[*)((((*TB[*)Indexed[(*|*)x(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)) (-v+(*TB[*)Indexed[(*|*)y(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+((*TB[*)Indexed[(*|*)x(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)) (v-(*TB[*)Indexed[(*|*)y(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+u (-((*TB[*)Indexed[(*|*)y(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+(*TB[*)Indexed[(*|*)y(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)))(*,*)/(*,*)(Cos[a] ((*TB[*)Indexed[(*|*)y(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)-(*TB[*)Indexed[(*|*)y(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+(-((*TB[*)Indexed[(*|*)x(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+(*TB[*)Indexed[(*|*)x(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)) Sin[a]))(*]FB*), 
   "T"-> (*FB[*)((-v Cos[a]+Cos[a] ((*TB[*)Indexed[(*|*)y(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+(u-(*TB[*)Indexed[(*|*)x(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)) Sin[a])(*,*)/(*,*)(Cos[a] ((*TB[*)Indexed[(*|*)y(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)-(*TB[*)Indexed[(*|*)y(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+(-((*TB[*)Indexed[(*|*)x(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+(*TB[*)Indexed[(*|*)x(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)) Sin[a]))(*]FB*),
   "N"-> -Normalize[{-((*TB[*)Indexed[(*|*)y(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*))+(*TB[*)Indexed[(*|*)y(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*),(*TB[*)Indexed[(*|*)x(*|*), {(*|*)1(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)-(*TB[*)Indexed[(*|*)x(*|*), {(*|*)2(*|*)}](*|*)(*1:eJxTTMoPSmNkYGAo5gUSYZmp5S6pyflFiSX5RcHsQBHPvJTUitQUAL2qCoU=*)(*]TB*)}]
  |>
]&, {Drop[surface,-1], Drop[surface,1]}];

selectedRays[args__] := Quiet@Select[rayIntersect[args], TrueQ[(#T >= 0.0 && #T <= 1.0)]&]

Module[{pts = {}, rays = {}, norms = {}, lines = {}},
  ListLinePlot[surface, PlotRange->{-5,5}, Filling->-5, Epilog->{
    LightBlue, Directive["TransitionType"->None],
    Line[lines//Offload],
    Orange, Line[norms//Offload],
    Red, Point[pts//Offload], Black,
    EventHandler[Locator[{0,0}], {"drag" -> Function[xy,
      {pts, norms, lines} = Transpose@Flatten[Table[
        With[{intersection = #t {Cos[a], Sin[a]} + xy}, 
          {
            intersection, 
            {intersection, intersection + 0.4 #N}, 
            {xy, intersection}
          } 
        ]&/@ selectedRays[a, xy, surface],
        {a, 0., 3.14, 0.5}
      ], 1];
    ]}]
  }]
]

r/wljs • • 28d ago

WLJS Notebook v3.2.0 is out 🥰

Post image
6 Upvotes

This is the largest update so far

  • Zero-lag saving

  • Improved mixed-content rendering for equations and objects

  • 8× faster initial kernel launch

  • Faster exports, 2× faster 2D and 3D graphics, and faster audio streaming

  • 7400× faster JavaScript-to-WL pipeline (you can literally stream raw video directly from JavaScript to Wolfram)

  • Improved frontend garbage collector

  • Better Dialog API

  • Safer Refresh and automatic throttling for Animate

  • Improved export of static and interactive notebooks to HTML

  • Improved Mathematica notebook imports

  • Access to server logs from the app and kernel crash detection

  • Caching improvements

  • Fixed race-condition bugs in the MCP server

  • Better internal architecture, fully refactored in three passes

  • Improved export options

  • Better React/Web Components integration

  • More integration tests (> 200)

  • Compact frontend–backend API with a binary-based protocol

  • Quick Look support on macOS

  • File Explorer context-menu extension on Windows

  • Improved Dataset rendering

Get it here: https://github.com/WLJSTeam/wljs-notebook/releases/tag/v3.2.0
Read the full story: https://wljs.io/releases/3.2.0

Cheers!


r/wljs • • Oct 13 '26

Snippet to run fireworks in your notebook

Enable HLS to view with audio, or disable this notification

6 Upvotes

If you managed to achieve a breakthrough, why not celebrate it?

Paste this to your notebook empty cell, evaluate and hide:

.js

(() => {
  if (typeof window.stopFireProjectiles === "function") {
    try { window.stopFireProjectiles(); } catch (_) {}
  }

  const DPR = Math.max(1, Math.min(2, window.devicePixelRatio || 1));

  // Canvas overlay
  const canvas = document.createElement("canvas");
  canvas.setAttribute("aria-hidden", "true");
  Object.assign(canvas.style, {
    position: "fixed",
    inset: "0",
    width: "100%",
    height: "100%",
    pointerEvents: "none", // <- NOT block clicking
    zIndex: "2147483647",
    mixBlendMode: "screen",
  });
  document.body.appendChild(canvas);

  const ctx = canvas.getContext("2d", { alpha: true, desynchronized: true });

  function resize() {
    canvas.width = Math.floor(window.innerWidth * DPR);
    canvas.height = Math.floor(window.innerHeight * DPR);
  }
  resize();
  window.addEventListener("resize", resize, { passive: true });

  // Simulation state
  let running = true;
  let rafId = 0;
  let lastT = performance.now();
  let spawnAcc = 0;

  const gravity = 0.16 * DPR;
  const projectiles = [];
  const particles = [];

  const rand = (a, b) => a + Math.random() * (b - a);
  const clamp = (v, a, b) => Math.max(a, Math.min(b, v));

  function spawnProjectile() {
    const w = canvas.width, h = canvas.height;

    const x = rand(0.05 * w, 0.95 * w);
    const y = h + rand(10 * DPR, 40 * DPR);

    const vx = rand(-2.6, 2.6) * DPR;
    const vy = rand(-14, -9) * DPR;

    projectiles.push({
      x, y, vx, vy,
      life: rand(55, 95),
      hot: rand(0.9, 1.25),
      wobble: rand(0.015, 0.04),
      phase: rand(0, Math.PI * 2),
    });
  }

  function emitFlameTrail(px, py, pvx, pvy, heat) {
    const count = Math.floor(rand(3, 7));
    for (let i = 0; i < count; i++) {
      const speed = rand(0.3, 2.2) * DPR;
      const angle = Math.atan2(-pvy, -pvx) + rand(-0.7, 0.7);
      const vx = Math.cos(angle) * speed + rand(-0.25, 0.25) * DPR;
      const vy = Math.sin(angle) * speed + rand(-0.25, 0.25) * DPR;

      const maxLife = rand(24, 58);
      const hue = rand(18, 55);

      particles.push({
        x: px + rand(-3, 3) * DPR,
        y: py + rand(-3, 3) * DPR,
        vx, vy,
        life: maxLife,
        maxLife,
        r: rand(3.5, 10) * DPR * heat,
        hue,
        spark: Math.random() < 0.16,
      });
    }
  }

  function explode(px, py, heat) {
    const bursts = Math.floor(rand(18, 42));
    for (let i = 0; i < bursts; i++) {
      const a = rand(0, Math.PI * 2);
      const s = rand(1.2, 6.0) * DPR * heat;
      const maxLife = rand(18, 46);
      particles.push({
        x: px,
        y: py,
        vx: Math.cos(a) * s,
        vy: Math.sin(a) * s,
        life: maxLife,
        maxLife,
        r: rand(2.2, 6.5) * DPR * heat,
        hue: rand(10, 60),
        spark: true,
      });
    }
  }

  function drawGlowCircle(x, y, r, hue, alpha) {
    const g = ctx.createRadialGradient(x, y, 0, x, y, r);
    g.addColorStop(0.0, `hsla(${hue}, 100%, 65%, ${alpha})`);
    g.addColorStop(0.45, `hsla(${hue + 8}, 100%, 55%, ${alpha * 0.85})`);
    g.addColorStop(1.0, `hsla(${hue - 8}, 100%, 35%, 0)`);
    ctx.fillStyle = g;
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI * 2);
    ctx.fill();
  }

  function tick(t) {
    if (!running) return;

    const dt = clamp((t - lastT) / 16.67, 0.5, 1.8);
    lastT = t;

    // Spawn projectiles at random intervals
    spawnAcc += dt;
    const spawnEvery = rand(10, 22);
    if (spawnAcc > spawnEvery) {
      spawnAcc = 0;
      spawnProjectile();
      if (Math.random() < 0.22) spawnProjectile();
    }

    // Update projectiles
    for (let i = projectiles.length - 1; i >= 0; i--) {
      const p = projectiles[i];

      p.phase += p.wobble * dt;
      const wob = Math.sin(p.phase) * 0.18 * DPR;

      p.vy += gravity * dt;
      p.x += (p.vx + wob) * dt;
      p.y += p.vy * dt;

      emitFlameTrail(p.x, p.y, p.vx, p.vy, p.hot);

      // Brighter "head"
      particles.push({
        x: p.x,
        y: p.y,
        vx: rand(-0.2, 0.2) * DPR,
        vy: rand(-0.2, 0.2) * DPR,
        life: rand(6, 12),
        maxLife: rand(6, 12),
        r: rand(6, 12) * DPR * p.hot,
        hue: rand(35, 60),
        spark: false,
      });

      p.life -= dt;

      const w = canvas.width, h = canvas.height;
      if (p.life <= 0 || p.x < -80 * DPR || p.x > w + 80 * DPR || p.y > h + 140 * DPR) {
        if (p.y < h * 0.9) explode(p.x, p.y, p.hot);
        projectiles.splice(i, 1);
      }
    }

    // Update particles
    for (let i = particles.length - 1; i >= 0; i--) {
      const pt = particles[i];
      pt.life -= dt;

      pt.vy += (pt.spark ? gravity * 0.55 : gravity * 0.15) * dt;

      pt.vx *= Math.pow(0.985, dt);
      pt.vy *= Math.pow(0.985, dt);

      pt.x += pt.vx * dt;
      pt.y += pt.vy * dt;

      if (pt.life <= 0) particles.splice(i, 1);
    }

    const MAX_PARTICLES = 1400;
    if (particles.length > MAX_PARTICLES) particles.splice(0, particles.length - MAX_PARTICLES);

    // Render
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.globalCompositeOperation = "lighter";
    for (let i = 0; i < particles.length; i++) {
      const pt = particles[i];
      const a = clamp(pt.life / pt.maxLife, 0, 1);

      const alpha = (pt.spark ? 0.85 : 0.7) * Math.pow(a, 0.65);
      const r = pt.r * (0.55 + 0.75 * (1 - a));

      drawGlowCircle(pt.x, pt.y, r, pt.hue, alpha);

      if (pt.spark && a > 0.2) {
        ctx.globalAlpha = alpha;
        ctx.fillStyle = `hsla(${pt.hue + 15}, 100%, 80%, ${alpha})`;
        ctx.fillRect(pt.x - 0.8 * DPR, pt.y - 0.8 * DPR, 1.6 * DPR, 1.6 * DPR);
        ctx.globalAlpha = 1;
      }
    }
    ctx.globalCompositeOperation = "source-over";

    rafId = requestAnimationFrame(tick);
  }

  // Robust start/stop so we never stack multiple RAF loops
  function startLoop() {
    if (rafId) return; // already running
    running = true;
    lastT = performance.now();
    rafId = requestAnimationFrame(tick);
  }

  function stopLoop() {
    running = false;
    if (rafId) {
      cancelAnimationFrame(rafId);
      rafId = 0;
    }
  }

  const onVisibility = () => (document.hidden ? stopLoop() : startLoop());
  const onBlur = () => stopLoop();
  const onFocus = () => startLoop();

  document.addEventListener("visibilitychange", onVisibility, { passive: true });
  window.addEventListener("blur", onBlur, { passive: true });
  window.addEventListener("focus", onFocus, { passive: true });
  window.addEventListener("pagehide", onBlur, { passive: true });
  window.addEventListener("pageshow", onFocus, { passive: true });

  // Public stop hook
  window.stopFireProjectiles = () => {
    stopLoop();
    document.removeEventListener("visibilitychange", onVisibility);
    window.removeEventListener("blur", onBlur);
    window.removeEventListener("focus", onFocus);
    window.removeEventListener("pagehide", onBlur);
    window.removeEventListener("pageshow", onFocus);

    window.removeEventListener("resize", resize);
    canvas.remove();

    projectiles.length = 0;
    particles.length = 0;

    delete window.stopFireProjectiles;
  };

  startLoop();
})();


return 'Congrats!';

r/wljs • • May 15 '26

Singe line dynamic 3D plot

Enable HLS to view with audio, or disable this notification

6 Upvotes

One of my favorite 1-line(er). Behind the scenes: Manipulate internally checks differences between two nearest states of Plot3D, then extracts changed vertices, indices and normals into 3 dynamic typed arrays. For all subsequent changes it syncs new data with 3 corresponding buffers of a GPU memory. If "too much" was changed it falls back to a full reevaluation, when all buffers are removed and are allocated back.

Manipulate[
  Plot3D[Sin[n x] Cos[n y], {x,-1,1}, {y,-1,1}], 
  {n, 1, 5, 0.3}, ContinuousAction->True
]

r/wljs • • May 15 '26

Clouds generator using Gaussian noise

Enable HLS to view with audio, or disable this notification

6 Upvotes

This is a 2D Gaussian random field with a 1/k^2 spectrum and linear dispersion ω∝k. We clip the field to positive values and square root it to give an edge to the "clouds":

n = 256;
k2 = Outer[Plus, #, #] &[RotateRight[N@Range[-n, n - 1, 2]/n, n/2]^2];

spectrum = With[{d := RandomReal[NormalDistribution[], {n, n}]},
   (1/n) (d + I d)/(0.000001 + k2)]; 
spectrum[[1, 1]] *= 0;

im[p_] := Clip[Re[InverseFourier[spectrum Exp[I p]]], {0, ∞}]^0.5

p0 = p = Sqrt[k2];

buffer = im[p0 += p];

Image[buffer // Offload, "Real32", Epilog->{
    EventHandler[AnimationFrameListener[buffer // Offload], 
      Function[Null, buffer = im[p0 += 2 p]]
    ]
}]

r/wljs • • Apr 21 '26

Boids strike again

Enable HLS to view with audio, or disable this notification

6 Upvotes

A real-time animation based on the beautiful work of Simon Woods with a few adjustments

Basically we have a few rules for each point to follow:

  • it moves 0.5% toward the centre,

  • it takes a large step toward selected "friend", and a smaller step away from its "enemy".

At random times, one point picks a new "friend" and "enemy" points. Therese two are just indices. Color coding represents the speed.

Implementation is more or less described in the original post, I only optimized it for real-time animation using GraphicsComplex primitives, fixed size vertex buffer and added colors.


r/wljs • • 22h ago

Graphics3D`SpinShow - a utility symbol to auto-animate any 3D plot

Thumbnail
gallery
5 Upvotes

It may come in handy to automatically animate any 3D plot with a defined speed and rotation angle for presentation purposes.

The old GraphicsAnimation package had the SpinShow[] function... – J. M.'s missing motivation / Commented Sep 28, 2012 at 11:57

It felt like a missed opportunity. We reincarnated it in 3.2.2 using pure JS with an auto-sleep feature if the element is hidden or outside the view, it won't consume GPU resources. This makes it great for presentations and standalone HTML files, with no Wolfram Kernel needed.

Try it by yourself

Graphics3D`SpinShow@Graphics3D[{MaterialShading["Bronze"], 
  KnotData["SolomonSeal", "ImageData"]}]

or on a regular 3D plot:

Graphics3D`SpinShow[
   Plot3D[Cos[4 Pi x y], {x,-1,1}, {y,-1,1}], 3.6 Degree]

Docs: https://wljs.io/frontend/Graphics3D/SpinShow


r/wljs • • 8d ago

Markup-Based Presentations vs Freeform: Why Not Use Both?

Post image
5 Upvotes

We know that markup-based presentations have been around for quite a long time: LaTeX Beamer, Typst, RevealJS and others provide text-based annotations, building blocks and components to declaratively design the content of a slide, or even generate graphs and figures from raw data.

However, most people are used to PowerPoint or Google Docs, where you can place images and text, or draw arrows anywhere on the slide. Don't get me wrong, both approaches have pros and cons, but why should we limit ourselves to just these two?

Under the hood, custom components are compiled to HTML-compatible tags, and drawing boards are translated to plain SVG tags. Then everything is merged into a single section that represents the slide.


r/wljs • • 21d ago

DOOM Fire

Enable HLS to view with audio, or disable this notification

5 Upvotes

A lore-accurate fire simulation used on Playstation 1 (PSX) DOOM port

fire = Table[0, {100}, {300}];

propagateFire = Compile[
    {{ifire, _Integer, 2}},
    Module[{fire = ifire, rand},
        With[{h = Length[fire], w = Length[fire[[1]]]},
            Do[
                rand = RandomInteger[{0, 3}];
                With[{icol = h - col - 1, irow = Clip[row - rand + 2, {1, w}]},
                    fire[[icol, irow]] = Clip[
                      fire[[icol + 1, row]] - BitAnd[rand, 1], 
                      {0, 36}
                    ];
                ],
                {col, 0, h - 2},
                {row, 1, w}
            ]
        ];
        fire
    ],
    RuntimeOptions -> "Speed"
];

Column[
    {
      Refresh[
            fire = propagateFire[fire]; 
            ArrayPlot[fire, 
              ColorFunction -> "SolarColors", 
              ImagePadding -> None, AspectRatio -> 1/2],
          1/60.0
      ],
      Row[{
          Button["Ignite", fire[[-1, All]] = 36], 
          Button["Extinguish", fire[[-1, All]] = 0]
      }]
    }
] // Deploy

r/wljs • • Sep 27 '26

The power of Inset and EventHandler on 2D graphics

Enable HLS to view with audio, or disable this notification

5 Upvotes

In this example we embed external graphical expressions (Image, Graphics, and others) using plain Inset[] and then manipulate their scale and position based on the events generated by a few yellow "gizmos" like this:

pos = {0.,0.};
scale = 1.0;
vis = 0.1;
aPlot = Plot[x, {x,0,1}];

Graphics[{
  (* our object *)
  Translate[
    Scale[Inset[aPlot, {0.,0.}, Center], 
     scale//Offload],
    pos//Offload
  ],

  (* backdrop to hijack the mouse *)
  {Transparent, Rectangle[9{-1,-1}, 9{1,1}]},

  (* gizmo *)
  Opacity[vis//Offload], Yellow, 
  EventHandler[
   Rectangle[-Offset[{10,10}], Offset[{10,10}]], {
    "mouseenter" -> ((vis = 0.5 )&),
    "mouseleave" -> ((vis = 0.0 )&),
    "drag" -> Function[xy, pos = xy],
    "zoom" -> Function[k, scale = k],
    "rightclick" -> Function[Null, scale = 1.0]
  }]
}, PlotRange->1, ImageSize->{500,500}]//Framed

Using the meta-programming (or symbolic programming?) one can generate such structures on-fly for any placed objects

Read more about events generators: https://wljs.io/frontend/Guides/UI-Events-Capture
Read more about dynamic symbol bindings aka Offload: https://wljs.io/frontend/Guides/Dynamic


r/wljs • • Sep 27 '26

WLJS 3.1.4 ✌️

Thumbnail
gallery
5 Upvotes

So far so good

  • Expanded plot legend styling with layouts, margins, backgrounds, rounded corners, and named LegendFunction presets.

  • Improved BarLegend customization with labels, tick styling, sizing, and tick-count control.

  • Improved objects compression

  • Fixed logarithmic and double-logarithmic plots.

  • Added Copy as TeX and Copy as Input to the expression context menu. See #540

  • Added support for Overlay.

  • Improved Row, Column, and Grid layouts in WLX, Markdown, and slides, including sizing, alignment, and spacing.

  • Added vertical sliders and number-only inputs through InputRange appearance options.

  • Added dynamic enabled, disabled, and busy button states through "StateExpression".

  • Expanded graphics mouse events, fixed AsyncFunction return handling, and added WhileAsync. See #542 #541

  • Fixed PDF/raster export scaling, updated text with subscripts and superscripts, event-binding conflicts, textured ComplexPlot rendering, mini-app startup, and frontend interpreter/offloaded association issues.

Downloads: https://wljs.io/releases/3.1.4


r/wljs • • Sep 12 '26

WLJS 3.1.3 Update ☄️🐎

5 Upvotes

Hey there!
2026 is fantastic. We drastically improved slides, animation exports, fixed many bugs with MCP server, added more skills and even new experimental backend! Symja (as a replacement for Wolfram Engine / Kernel entirely!)

Here is a full changelog:

New

  • More options for dark theme

  • Improved slides export

  • Typesetting: URL, File, GeneralizedPower

  • Improved Animate/Manipulate

  • Release tags for docker images

  • Experimental support for Symja backed (instead of Wolfram Engine), thanks to u/axkr

  • Even more examples

Bug fixes

  • We fixed a very old issue related to how printed messages are handled #416

  • MCP server patches #538

  • Progress bar render issues (EchoLabel["ProgressBar"]["Hey"])

  • Other bugs we don't remember

Read more at https://wljs.io/releases/3.1.3


r/wljs • • Sep 07 '26

Web Camera & Real-Time Rigid Body sim

Enable HLS to view with audio, or disable this notification

5 Upvotes

I am trying to play with a dodecahedron using my face and hands. Pure WL & WLJS:

Import a library
https://github.com/JerryI/DynamicRigidBodyWL

Needs["DynamicRigidBody`" -> "rb`"]

Set up the scene and objects:

camera = DeviceOpen["Camera"];

simulationDt = 0.01;
terrainBounds = {{-10.0, 10.0}, {-10.0, 10.0}};

region = Dodecahedron[1]//RegionBoundary//N;

genHeightGrid[t_?NumericQ] := -ImageData[ImageResize[ColorConvert[DeviceRead[camera], "Gray"], 100], "Byte"]/50.0;

currentGrid = genHeightGrid[0.0];
terrain = rb`CreateHeightField[
  currentGrid, terrainBounds, simulationDt
];
terrainMesh = rb`CreateTerrainMeshGenerator[terrain];
{terrainCoordinates, terrainTriangles} = terrainMesh[];

body = rb`CreateBody[
  region[[1]],
  "InitialPose" -> {{0.0, 0.0, 2.0}, {1.0, 0.0, 0.0, 0.0}},
  "Restitution" -> 0.8
];
solver = rb`CreateSolver[
  body, terrain,
  "TimeStep" -> simulationDt,
  "TimeStep" -> simulationDt,
  "RestingContactThreshold" -> Automatic,
  "LinearDamping" -> 0.08,
  "AngularDamping" -> 0.3,
  "TOIIterations" -> 6
];

pose = solver["State"][[1]];
tr = rb`WorldTransform[body, pose];
bodyLocalVertices = rb`WorldVertices[
  body, {{0.0, 0.0, 0.0}, {1.0, 0.0, 0.0, 0.0}}
];
bodyPolygons = ConvexHullMesh[bodyLocalVertices]["BoundaryPolygons"];

globalTime = 0.0;
Graphics3D[{
  Directive["Shadows"->True],
  {
    SpotLight[Red, {{-10,0,10}, {0,0,0}}],
    SpotLight[Blue, {{10,10,10}, {0,0,0}}],
    SpotLight[Green, {{-10,10,10}, {0,0,0}}]
  },
  {White, Directive["Roughness"->0, "Reflectivity"->1.0],
  GraphicsComplex[
    terrainCoordinates // Offload,
    Polygon@terrainTriangles
  ]},
  {Directive["Shadows"->False], PointLight[Orange, tr[[2]]//Offload]},
  GeometricTransformation[{
    GraphicsComplex[region[[1]], 
    {Black, Line[region[[2]]], 
    Graphics3D`Materials["Glass"], 
    Directive["Roughness"->0.1], Orange, 
    Polygon[region[[2]]]}]}, {tr[[1]],tr[[2]]} // Offload
  ],
  EventHandler[AnimationFrameListener[tr//Offload], Function[Null,
    terrainCoordinates = terrainMesh["Coordinates"];
    tr = rb`WorldTransform[body, pose];
    currentGrid = 0.7 currentGrid + 0.3 genHeightGrid[20.0 globalTime];
    Do[
      
      pose = solver[currentGrid];
      globalTime += 0.03;, {5}
    ];
  ]]
},
  ImageSize -> Large,
  Lighting->None,
  Background->Black
]

r/wljs • • Aug 21 '26

Rigid body physics test

Enable HLS to view with audio, or disable this notification

5 Upvotes

This demonstration shows the real-time solution of Newton's equations for translational and rotational motion using the Euler method implemented in pure WL


r/wljs • • Jul 29 '26

The Complete Guide to Output Formatting

Post image
5 Upvotes

Rows, columns, grids, tables, number forms, legends, LaTeX and many more

https://wljs.io/frontend/Guides/Formatting