问题描述
是否有某种方法可以在Jupyter Notebook中获得google.colab.output.eval_js
的行为?我有一些使用IPython.display
来让用户绘制图像的代码。当按下按钮时,JS将图像的内容另存为data
,然后我在Python中使用data = eval_js("data")
将这些内容提取到Python中。我正在尝试在Jupyter Notebook中复制该行为。我将完整的代码放在下面。
from IPython.display import HTML,Image
from google.colab.output import eval_js
canvas_html = """
<canvas width=%d height=%d style="background-color:rgb(240,240,240)"=></canvas>
<button>Guess Number</button>
<script>
var canvas = document.querySelector('canvas')
var ctx = canvas.getContext('2d')
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=280,h=280,line_width=20):
display(HTML(canvas_html % (w,h,line_width)))
data = eval_js("data")
# do sth with the variable in python ...
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)