Skip to content

Instantly share code, notes, and snippets.

@jacius
Last active July 18, 2021 05:49
Show Gist options
  • Save jacius/4750859 to your computer and use it in GitHub Desktop.
Save jacius/4750859 to your computer and use it in GitHub Desktop.
HTML5 canvas with Chicken Scheme

Simple example of using Chicken Scheme to generate HTML and JS, using the html-tags and spock eggs. This example is based on the MDN canvas tutorial.

You will need:

Run make to generate the HTML and JS files, then open "index.html" in a web browser.

Optionally, you can use Guard to automatically generate the HTML/JS when the Scheme files change. gem install guard then run guard inside the source directory.

(define (draw)
(define canvas (%inline "document.getElementById" "canvas"))
(define ctx (%inline ".getContext" canvas "2d"))
(when ctx
(set! (.fillStyle ctx) "rgb(200,0,0)")
(%inline ".fillRect" ctx 10 10 55 50)
(set! (.fillStyle ctx) "rgba(0, 0, 200, 0.5)")
(%inline ".fillRect" ctx 30 30 55 50)))
(set! window.onload (callback draw))
guard 'shell' do
watch(/(.*)\.scm/) {|m| `make #{m[1]}` }
end
(require-library html-tags spock)
(import html-tags spock)
(display "<!DOCTYPE html>")
(display
(<html>
(<head>
(<spock-header>)
(<style> "canvas { border: 1px solid black; }")
(<script> type: "text/javascript" src: "canvas-test.js"))
(<body>
(<p> "Say hello to my little canvas.")
(<canvas>
id: "canvas" width: 150 height: 150
"Wow. Your browser doesn't support HTML5 canvas. That's pretty lame."))))
generated = index.html canvas-test.js spock-runtime-min.js
all: $(generated)
clean:
rm $(generated)
%.html: %.html.scm
csi -s $< > $@
%.js: %.js.scm
chicken-spock $< > $@
spock-runtime-%.js:
cp `chicken-spock -library-path`/$@ $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment