有什么方法可以得到的行为google.colab.output.eval_js
在 Jupyter 笔记本中?我有一些使用的代码IPython.display
让用户绘制图像。当按下按钮时,JS 将图像内容保存为data
然后我用data = eval_js("data")
在 Python 中将该内容提取到 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 ...
Go for pip install Js2Py
then,
from js2py import eval_js
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)