Skip to content

Instantly share code, notes, and snippets.

@imflash217
Last active April 30, 2021 22:17
Show Gist options
  • Save imflash217/a40b8f0d23567908fc17dcce84f3de6e to your computer and use it in GitHub Desktop.
Save imflash217/a40b8f0d23567908fc17dcce84f3de6e to your computer and use it in GitHub Desktop.
canvas, jupyter-notebook
from IPython.display import HTML, Image
from google.colab.output import eval_js
from base64 import b64decode

# setup the canvas
canvas_html = """
<canvas width=%d height=%d></canvas>
<button>Done!</button>
<script>
var canvas = document.querySelector('canvas')
var ctx = canvas.getContext('2d')
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 448, 448);
ctx.strokeStyle = "white";
ctx.lineCap = 'round';
ctx.lineWidth = %d
var button = document.querySelector('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=>{
  button.onclick = ()=>{
    resolve(canvas.toDataURL('image/png'))
  }
})
</script>
"""

def draw(filename='drawing.png', w=224, h=224, line_width=10):
  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)

# call this to have notebook wait for drawing input
draw()

#you can then import the image and do what you need with it!
#image = cv2.imread("drawing.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment