javascript - Jupyter Notebook 中的 Google Colabs eval_js?

标签 javascript python jupyter-notebook google-colaboratory

有没有办法获得 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 ...

最佳答案

前往 pip install Js2Py然后,from js2py import eval_js

关于javascript - Jupyter Notebook 中的 Google Colabs eval_js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63561206/

相关文章:

javascript - Scrapy 飞溅不返回结果

javascript - 表单中自动保存按钮之前的 2 秒间隔

python - Django - <FieldFile : None> While Updating a row in Employee table

python - 在 Python 中迭代打印两种数据类型

split - Jupyter Notebook Ctrl+Shift+-(拆分单元格)不起作用

javascript - jstools build - JavaScript 在编译后出现问题

javascript - 在 React 上,如何在功能/无状态组件上的组件挂载上调用函数?

python - 如何将命令永久存储在 Python REPL/提示符中?

python - 如何以编程方式在 Jupyter 笔记本中生成 Markdown 输出?

jupyter-notebook - 是否可以在 Jupyter Notebook 中缩放粘贴的图像?