Brython: Python for the Browser
What Is a Transpiler?
Getting Started with Brython
Working with HTML
Brython has first-class support for HTML elements. After importing the html module, you have native access to all the HTML4 and HTML5 tags. We instantiate an element by calling the full name in all caps. You can include an option innerText string and an attribute list. Below we have an anchor that has 'Python' as innerText and navigates to python.org. The next link in the snippet is an alias for element.appendChild.
link = html.A('Python', href='http://www.python.org') doc <= link
The following is a simple script that changes the address an anchor tag links to. One of the fun things about using Brython is that you have a shortcut to document.getElementById, thanks to the doc object. You can query by id by calling doc["elemId"] or by tag name with doc[TAGNAME]. Below is an example instantiating a canvas and setting some properties.
canvas = html.CANVAS() canvas.height = 480 canvas.width = 640 ctx = canvas.getContext('2d') doc['gameboard'] <= canvas
Working with Existing JS Objects
a = JSObject(eval("String('123s')"))
Creating a Simple Canvas Game/Project
To assess how Brython would work in a real-world situation, I decided to port one of my smaller Canvas2D demos to Brython, a binary clock originally made using Amino.js. Check out my article for more information.
def lpad(s, length): while (len(s) < length): s = "0" + s return s