Simple Canvas DrawingSince version 184.108.40.206, PicoLisp comes with a library for drawing 2D images into HTML5 <canvas> elements. It was initially needed for a project displaying the results of real-time measurements on embedded systems.
This article will only explain the underlying principles, and show some examples. General information about the <canvas> element is available at https://developer.mozilla.org/en-US/docs/HTML/Canvas.
Using the LibraryTo use it, just do the following 4 things:
- Include "@lib/canvas.l" in your application.
(load "@lib/canvas.l")This will define a set of Lisp functions, of the form e.g.
strokeRect(x, y, width, height)
- Define a function named drawCanvas:
(de drawCanvas (Id Dly) (make ... ) )This name "drawCanvas" is mandatory. This function will be used to draw all canvas contents. If there are several instances of <canvas> in the application, drawCanvas can tell them apart by the canvas ID it receives in its first argument.
drawCanvas should return a list of commands, which is typically built with make.
- Create <canvas> element(s) on your pages, each with a unique ID, and a
width and a height:
(<canvas> "someId" 400 300)
- Let the canvas drawing loop start when the page is loaded. This can be done
either with 'onload' in the page <body> tag:
A Minimal ExampleTo see the effect of the above four steps, put the following into a file called draw2Rects.l:
(load "@lib/http.l" "@lib/xhtml.l" "@lib/form.l" "@lib/canvas.l") (de drawCanvas (Id Dly) (make (csStrokeStyle "blue") (csStrokeRect 0 0 400 300) (csFillStyle "red") (csFillRect 100 100 200 100) ) ) (de canvasTest () (action (html 0 "Canvas Test" "@lib.css" '((onload . "drawCanvas('$testID', -1)")) (form NIL (<canvas> "$testID" 400 300) ) ) ) ) (de work () (app) (redirect (baseHRef) *SesId "!canvasTest") ) (server 8080 "!work")Start it as
$ pil draw2Rects.l +Then point your browser to http://localhost:8080. You will see a large blue rectangle surrounding a smaller red rectangle.
Note: 'httpGate' must be running on your system for this to work, because XMLHttpRequests fail if the port changes (same-origin policy). Start it (as root) with:
# /usr/lib/picolisp/bin/httpGate 80 8080
A Small ExampleA second, more extensive, example I have installed on the server, so that it can be tried online: http://canvas.picolisp.com.
It shows a page with two tabs. The canvas on the first tab "Zappel" plots a graph of random numbers, at a rate of about 4 per second. Two buttons, "Faster" and "Slower", can be used to change the rate, by halving or doubling the delay.
The second tab "Single" stops the continuous process, and allows you to single-step the plot with the "Step" button.
The three "Pos" buttons at the bottom can be used to "calibrate" the graph vertically, by shifting it up or down similar to the "Y-Pos" knob of an oscilloscope.
I will not comment the code in detail here, but leave it as an exercise to the reader. Here is the complete file: