draw.py

from IPython.display import HTML, Image from google.colab.output import eval_js from base64 import b64decode canvas_html = """ <canvas width=%d height=%d style="border: 1px solid black;"></canvas> <button id='finishButton'>Finish</button> <button id='circleButton'>Circle</button> <button id='drawButton'>Draw</button> <input type="number" id='radius'>Radius of circle</input> <script> var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') ctx.lineWidth = %d var button = document.getElementById('finishButton') var buttonCircle= document.getElementById('circleButton') var buttonDraw= document.getElementById('drawButton') var mouse = {x: 0, y: 0} var selected='draw' canvas.addEventListener('mousemove', function(e) { mouse.x = e.pageX - this.offsetLeft mouse.y = e.pageY - this.offsetTop }) canvas.addEventListener('mousedown', function(e) { if(selected=='draw'){ ctx.beginPath() ctx.moveTo(mouse.x, mouse.y) canvas.addEventListener('mousemove', onPaint) } if(selected=='circle'){ mouse.x = e.pageX - this.offsetLeft mouse.y = e.pageY - this.offsetTop ctx.beginPath() ctx.arc(mouse.x, mouse.y, document.getElementById('radius').value, 0, 2 * Math.PI) ctx.fill() } }) canvas.onmouseup = ()=>{ canvas.removeEventListener('mousemove', onPaint) } var onPaint = ()=>{ ctx.lineTo(mouse.x, mouse.y) ctx.stroke() } var data = new Promise(resolve=>{ button.onclick = ()=>{ resolve(canvas.toDataURL('image/png')) } buttonCircle.onclick = ()=>{ selected='circle' } buttonDraw.onclick = ()=>{ selected='draw' } }) </script> """ def draw(filename='drawing.png', w=400, h=200, line_width=1): display(HTML(canvas_html % (w, h, line_width))) data = eval_js("data") binary = b64decode(data.split(',')[1]) with open(filename, 'wb') as f: f.write(binary) return len(binary)
Drawing on Google Colab

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.