Skip to content

Instantly share code, notes, and snippets.

@ZhuoyueLyu
Forked from korakot/draw.py
Last active December 28, 2021 10:35
Show Gist options
  • Save ZhuoyueLyu/b22bb062fd8497aa94713320329a0ede to your computer and use it in GitHub Desktop.
Save ZhuoyueLyu/b22bb062fd8497aa94713320329a0ede to your computer and use it in GitHub Desktop.
Drawing on Google Colab
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 #000000;"></canvas>
<button id="finish-button">Finish</button>
<button id="clear-button">Clear</button>
<script>
var canvas = document.querySelector('canvas')
var ctx = canvas.getContext('2d')
ctx.lineWidth = %d
ctx.lineCap = "round" // stroke shape
ctx.fillStyle = "white" // color of canvas background
ctx.fillRect(0, 0, canvas.width, canvas.height)
var finishButton = document.getElementById('finish-button')
var clearButton = document.getElementById('clear-button')
var mouse = {x: 0, y: 0}
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft
mouse.y = e.pageY - this.offsetTop
})
canvas.onmousedown = ()=>{
ctx.beginPath()
ctx.moveTo(mouse.x, mouse.y)
canvas.addEventListener('mousemove', onPaint)
}
canvas.onmouseup = ()=>{
canvas.removeEventListener('mousemove', onPaint)
}
var onPaint = ()=>{
ctx.lineTo(mouse.x, mouse.y)
ctx.stroke()
}
var data = new Promise(resolve=>{
finishButton.onclick = ()=>{
resolve(canvas.toDataURL('image/png'))
}
clearButton.onclick = ()=>{
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white" // color of canvas background
ctx.fillRect(0, 0, canvas.width, canvas.height)
}
})
</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)
@Github-user-12
Copy link

Hello,
Is there a way to add the ability to also draw with a touch screen?
Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment