Skip to content

JavaScript: what Basthon adds ​

This page describes what Basthon adds to JavaScript and the differences with the console of a browser. To discover the kernel through examples, see JavaScript in Basthon.

The basthon object ​

Always available (not to be confused with the basthon Python module).

FunctionRole
basthon.sleep(seconds)pauses the program
basthon.createCanvas(width, height)creates a canvas (canvas.getContext("2d") to draw)
basthon.display(canvas)shows the canvas in its current state (an image)
basthon.displayLiveCanvas(canvas)shows a live canvas: it stays up to date after the run and receives the mouse and the keyboard
basthon.download(content, name)downloads a file called name whose content is given: a string (the text of the file) or bytes (Uint8Array)

Live canvases ​

A canvas shown with basthon.displayLiveCanvas behaves like a canvas of a web page:

  • whatever is drawn on it after the run is shown, for instance in a requestAnimationFrame animation loop;
  • mouse events (mousedown, mousemove, click…) are sent to the canvas (canvas.addEventListener), with clientX and clientY in canvas coordinates;
  • keyboard events (keydown…) are sent to canvas.ownerDocument.
js
const canvas = basthon.createCanvas(300, 200);
const ctx = canvas.getContext("2d");
let x = 0;
function frame() {
  ctx.clearRect(0, 0, 300, 200);
  ctx.fillRect(x, 90, 20, 20);
  x = (x + 2) % 300;
  requestAnimationFrame(frame);
}
frame();
basthon.displayLiveCanvas(canvas);

Differences with the console of a browser ​

The code runs in an environment separate from the page (a worker):

  • there is no web page: no document, nor window.alert; prompt("Question?") asks the user for an input;
  • console.log and console.error write to the output, and the value of the last expression is shown;
  • let, const and class declarations stay available from one run to the next;
  • fetch gets data from the web (with await, in an async function);
  • there is no filesystem: the *.js files opened in Basthon are run when they are loaded (see Files and modules).