Skip to main content

Javascript

Type .js in the first line of an input cell

Try evaluating:

cell
.js
return 1 + 1;

or

.js
const dom = document.createElement('span');
dom.innerText = "Hello World";
dom.style.color = 'lightblue';

return dom;

GitHub repo
JavaScript code is evaluated as a module, which means all defined variables are isolated to the cell.

tip

To define global variables, use the window or core object:

window.variable = 1;

Output Cell

The return value from the function can be a JavaScript object or a DOM element. DOM elements will be rendered in the output cell.

.js
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

canvas.width = 500;
canvas.height = 500;

const ballRadius = 10;
let x = canvas.width / 2;
let y = canvas.height - 30;
let dx = 2;
let dy = -2;

function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}

let uid;

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();

if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}

x += dx;
y += dy;

uid = requestAnimationFrame(draw);
}

uid = requestAnimationFrame(draw);

this.ondestroy = () => {
cancelAnimationFrame(uid);
};

return canvas;

Context

There are a few useful built-in objects accessible from within a cell.

this.ondestroy

This property is called when a cell is destroyed. Assign a clean-up function to it:

this.ondestroy = () => {
// Clean up resources
};
danger

Always clean up any timers or animation loops using the this.ondestroy property. Otherwise, they will continue running even after the cell is reevaluated.

requestAnimationFrame

This is a commonly used JavaScript method to sync with the browser’s framerate and render graphics smoothly.

danger

Don’t forget to cancelAnimationFrame using the this.ondestroy method.

Communication with the Wolfram Kernel

You can define any function for the WLJS interpreter using JavaScript cells. Please refer to these guides:

Also see: