+<span id="jsdebug" style="display: none; position: fixed; right:0; bottom:0">Debug</span>
+
+<script><!--
+body = document.body
+dbg = document.getElementById("jsdebug")
+canvas = document.getElementById("canvas")
+data=document.getElementById("image_serialize")
+
+image = canvas.getContext("2d")
+mouse = 0
+image_serialize=""
+
+// start and current coordinates of a draw
+// serves for tracking, whether path ends close to its beginning
+stx=0, sty=0
+cux=0, cuy=0
+
+function setcol(c) {
+ this.c = c
+ image.strokeStyle = c
+ image.fillStyle = c
+ if ( c == "#FFF" ) image.lineWidth = 32
+ else image.lineWidth = 4
+ data.value += " stroke " + c + " stroke-width " + image.lineWidth
+}
+
+setcol("$tpy[color]")
+
+function relX(x){
+ if ( body.clientWidth >= 800 ){
+ return Math.floor(cscaleW * (x - canvas.offsetLeft))
+ } else {
+ return Math.floor(cscaleW * (x - canvas.offsetLeft + window.pageXOffset))
+ }
+}
+function relY(y){
+ if ( body.clientWidth >= 800 ){
+ return Math.floor(cscaleH * (y - canvas.offsetTop))
+ } else {
+ return Math.floor(cscaleH * (y - canvas.offsetTop + window.pageYOffset))
+ }
+}
+
+function draw(x, y) {
+ if ( mouse == 1){
+ cux=relX(x), cuy=relY(y)
+
+ image.lineTo( cux, cuy )
+ image.stroke()
+
+ image_serialize += " " + cux + "," + cuy
+ }
+}
+
+function drawstart(x, y) {
+ mouse = 1
+
+ cscaleW = canvas.width / canvas.clientWidth
+ cscaleH = canvas.height / canvas.clientHeight
+
+ stx=relX(x), sty=relY(y)
+
+ image.beginPath()
+ draw(x, y) // why must this not use relative Coords ???
+
+ image_serialize = " polyline"
+}
+
+function drawstop() {
+
+ // if path ends close to beginning ( < 50 px); then close path and fill
+ if ( mouse == 1 && Math.sqrt( Math.pow(stx - cux, 2) + Math.pow(sty - cuy, 2)) <= 50 && c !== "#FFF" ){
+ image.lineTo( stx, sty )
+ image.stroke()
+
+ image.globalAlpha = .5
+ image.fill()
+ image.globalAlpha = 1
+
+ image_serialize += " " + stx + "," + sty
+ data.value += " fill " + c + "8" + image_serialize
+ } else if (mouse == 1) {
+ data.value += " fill #0000 " + image_serialize
+ }
+ dbg.innerHTML = " stx: " + stx + " cux: " + cux + " sty: " + sty + " cuy: " + cuy
+
+ image.closePath()
+ image_serialize = ""
+ mouse = 0
+}
+
+window.addEventListener( 'mouseup', function() { drawstop() } )
+canvas.addEventListener( 'mousedown', function(e) { drawstart(e.clientX, e.clientY) } )
+canvas.addEventListener( 'mousemove', function(e) { draw(e.clientX, e.clientY) } )
+
+window.addEventListener( 'touchend', function() { drawstop() } )
+canvas.addEventListener( 'touchstart', function(e) { drawstart(e.touches[0].clientX, e.touches[0].clientY) } )
+canvas.addEventListener( 'touchmove', function(e) { e.preventDefault(); draw(e.touches[0].clientX, e.touches[0].clientY) } )
+--></script>