【问题标题】:js: Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exportedjs:未捕获的安全错误:无法在“HTMLCanvasElement”上执行“toDataURL”:可能无法导出受污染的画布
【发布时间】:2021-02-10 20:31:55
【问题描述】:

我正在使用 plotly 和 pyqt5(gui 开发),当我尝试下载/导出生成的图像时,出现以下消息:

js: Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

我用的是QtWebengine,下一个例子:

import plotly.offline as po
import plotly.graph_objs as go

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5 import QtCore, QtWidgets
import sys


def show_qt(fig):
    raw_html = '<html><head><meta charset="utf-8" />'
    raw_html += '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>'
    raw_html += '<body>'
    raw_html += po.plot(fig, include_plotlyjs=False, output_type='div')
    raw_html += '</body></html>'

    fig_view = QWebEngineView()
    # setHtml has a 2MB size limit, need to switch to setUrl on tmp file
    # for large figures.
    fig_view.setHtml(raw_html)
    fig_view.show()
    fig_view.raise_()
    return fig_view


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    fig = go.Figure(data=[{'type': 'scattergl', 'y': [2, 1, 3, 1]}])
    fig_view = show_qt(fig)
    sys.exit(app.exec_())

【问题讨论】:

    标签: python pyqt pyqt5 plotly qtwebengine


    【解决方案1】:

    这是一个警告,警告下载图像的方式(将其转换为字节)可能会导致安全错误,但在这种情况下您可以忽略它。如果要下载文件,则必须使用 QWebEnginePage 的 downloadRequested 信号:

    def handle_downloadRequested(item):
        path, _ = QtWidgets.QFileDialog.getSaveFileName(
            None, "Save File", item.suggestedFileName()
        )
        if path:
            item.setPath(path)
            item.accept()
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
    
        fig = go.Figure(data=[{"type": "scattergl", "y": [2, 1, 3, 1]}])
        fig_view = show_qt(fig)
        fig_view.page().profile().downloadRequested.connect(
            handle_downloadRequested
        )
        sys.exit(app.exec_())

    【讨论】:

      猜你喜欢
      • 2020-02-20
      • 1970-01-01
      • 2017-08-22
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2018-08-02
      • 2018-10-28
      相关资源
      最近更新 更多