Skip to content

JavaScript in Basthon ​

Open the console or the notebook in JavaScript (URL parameter kernel=js). Examples are in the gallery, and what Basthon adds (the basthon object, live canvases) is described on the JavaScript: what Basthon adds page.

The code runs in an environment separate from the page (a worker): console.log and console.error write to the output, the value of the last expression is shown, and let, const and class declarations stay available from one run to the next. There is no web page (no document), but the basthon object (not to be confused with the basthon Python module) provides the essentials (see the list of its functions), for instance to draw:

js
const canvas = basthon.createCanvas(200, 200);
const ctx = canvas.getContext("2d");
ctx.fillStyle = "tomato";
ctx.fillRect(50, 50, 100, 100);
basthon.display(canvas);

fetch gets data from the web (with await, in an async function).

What you can do ​

Interactive and animated canvases ​

A canvas shown with basthon.displayLiveCanvas stays alive after the run: whatever is drawn on it afterwards is shown (for instance with requestAnimationFrame for an animation), and it receives the mouse (with clientX and clientY in canvas coordinates) and the keyboard (on canvas.ownerDocument). Here, each click draws a disk (try it, post):

js
const canvas = basthon.createCanvas(400, 300);
const ctx = canvas.getContext("2d");
ctx.fillStyle = "orange";
ctx.fillRect(10, 10, 100, 50);
canvas.addEventListener("mousedown", (e) => {
  ctx.beginPath();
  ctx.arc(e.clientX, e.clientY, 10, 0, 2 * Math.PI);
  ctx.fill();
});
basthon.displayLiveCanvas(canvas);

The example of the gallery bounces balls: a click adds one, Esc clears them. Another one draws an analog clock (try it), and a notebook programs the game of life: a grid as an array of arrays, generations drawn side by side, then an animation where a click brings a cell to life or kills it (try it).

Simulations and charts ​

Math.random, arrays and their methods (map, reduce…) are enough to simulate a random experiment, and a canvas to draw its chart: a notebook compares the frequencies of the sums of two dice with the probabilities (try it).

Synchronous and asynchronous ​

async functions, await, fetch and promises work as in a browser: a notebook of the gallery compares synchronous and asynchronous runs (try it), another one tours the kernel (try it).

Completion ​

The Tab key completes variables, keywords and the properties of objects along a path of names: car.model.n offers name, Math.fl gives floor(.

Files and modules ​

The JavaScript kernel has no filesystem: extra files are not available. The open button (or the module URL parameter) runs *.js files when they are loaded.

Downloading a file ​

A file is downloaded with basthon.download("Hello!", "message.txt") (the content, text or bytes, then the name of the file).