Bokeh绘制的图片在前端展示

295 阅读1分钟

参考地址: blog.csdn.net/Cooldiok/ar… bokeh仓库地址:www.bootcdn.cn/bokeh/2.3.3… 页面效果:

image.png 原文: bokeh是python用来生成图表的库,类似于百度的echart,不过bokeh和后台代码结合的更紧密些,可以直接导出html文件。 在vue里显示bokeh的图表有两种办法: 1.使用iframe加载bokeh导出的html文件 缺点: ①因为不知道html内容的高度,事先定义高度的话会有滚动条,不美观 ②同时加载多个iframe时会造成页面的卡死,我本地加载5个页面会卡大概10秒,因为无法知道iframe内的内容什么时候加载完成,所以我也没法做loading界面去掩饰页面卡死 优点: ①简单! 2.把bokeh的div和script传给页面,在页面上进行渲染 使用bokeh的components功能,将div和js从plotting里分离出来 。。。 组件代码如下:

    <div class="boken-pic_wrap">
        <div v-html="html"></div>
    </div>
</template>

<script>
export default {
  name: 'BokenPic',
  data() {
    return {
        html: ""
    }
  },
  mounted() {
      this.initFn()
  },
  methods: {
      initFn() {
        //   const bokehVersion ='0.11.0' // '2.4.0-dev.2'
            // 在头部插入css代码
            // 因为要保持前端和后台的bokeh版本一致,所以使用了拼接cdn路径的方式
            // let link = document.createElement('link')
            // link.setAttribute('rel', 'stylesheet')
            // link.setAttribute('href', `https://cdn.bootcdn.net/ajax/libs/bokeh/${bokehVersion}/bokeh.min.css`)
            // link.setAttribute('type', 'text/css')
            // document.head.appendChild(link)
            // 在头部插入js代码
            let script = document.createElement('script')
            // script.setAttribute('src', `https://cdn.bootcdn.net/ajax/libs/bokeh/${bokehVersion}/bokeh.min.js`)
            script.setAttribute('src', `https://cdn.bootcdn.net/ajax/libs/bokeh/2.3.3/bokeh.min.js`)
            script.async = 'async'
            document.head.appendChild(script)
            // cdn的js加载完毕后再请求bokeh参数
            script.onload = () => {
                // this.axios.get('/yourUrl').then((response) => {
                    let response={
                        data: {'div': '\n<div class="bk-root" id="96528c78-aea5-4535-9310-b624defedc39" data-root-id="3105"></div>', 'script': '(function() {\n  var fn = function() {\n    Bokeh.safely(function() {\n      (function(root) {\n        function embed_document(root) {\n          \n        var docs_json = \'{"c31e6567-ed76-4ba2-8ca1-3d74fe6710f7":{"defs":[{"extends":null,"module":null,"name":"ReactiveHTML1","overrides":[],"properties":[]},{"extends":null,"module":null,"name":"FlexBox1","overrides":[],"properties":[{"default":"flex-start","kind":null,"name":"align_content"},{"default":"flex-start","kind":null,"name":"align_items"},{"default":"row","kind":null,"name":"flex_direction"},{"default":"wrap","kind":null,"name":"flex_wrap"},{"default":"flex-start","kind":null,"name":"justify_content"}]},{"extends":null,"module":null,"name":"TemplateActions1","overrides":[],"properties":[{"default":0,"kind":null,"name":"open_modal"},{"default":0,"kind":null,"name":"close_modal"}]},{"extends":null,"module":null,"name":"MaterialTemplateActions1","overrides":[],"properties":[{"default":0,"kind":null,"name":"open_modal"},{"default":0,"kind":null,"name":"close_modal"}]}],"roots":{"references":[{"attributes":{"below":[{"id":"3116"}],"center":[{"id":"3119"},{"id":"3123"},{"id":"3153"}],"left":[{"id":"3120"}],"renderers":[{"id":"3141"}],"title":{"id":"3106"},"toolbar":{"id":"3131"},"x_range":{"id":"3108"},"x_scale":{"id":"3112"},"y_range":{"id":"3110"},"y_scale":{"id":"3114"}},"id":"3105","subtype":"Figure","type":"Plot"},{"attributes":{},"id":"3151","type":"UnionRenderers"},{"attributes":{},"id":"3129","type":"HelpTool"},{"attributes":{"axis":{"id":"3120"},"dimension":1,"ticker":null},"id":"3123","type":"Grid"},{"attributes":{},"id":"3121","type":"BasicTicker"},{"attributes":{"data":{"x":[1,2,3,4,5],"y":[6,7,2,4,5]},"selected":{"id":"3152"},"selection_policy":{"id":"3151"}},"id":"3138","type":"ColumnDataSource"},{"attributes":{"bottom_units":"screen","fill_alpha":0.5,"fill_color":"lightgrey","left_units":"screen","level":"overlay","line_alpha":1.0,"line_color":"black","line_dash":[4,4],"line_width":2,"right_units":"screen","syncable":false,"top_units":"screen"},"id":"3130","type":"BoxAnnotation"},{"attributes":{"axis_label":"x","formatter":{"id":"3149"},"major_label_policy":{"id":"3148"},"ticker":{"id":"3117"}},"id":"3116","type":"LinearAxis"},{"attributes":{},"id":"3117","type":"BasicTicker"},{"attributes":{},"id":"3112","type":"LinearScale"},{"attributes":{"data_source":{"id":"3138"},"glyph":{"id":"3139"},"hover_glyph":null,"muted_glyph":null,"nonselection_glyph":{"id":"3140"},"view":{"id":"3142"}},"id":"3141","type":"GlyphRenderer"},{"attributes":{},"id":"3149","type":"BasicTickFormatter"},{"attributes":{"source":{"id":"3138"}},"id":"3142","type":"CDSView"},{"attributes":{},"id":"3148","type":"AllLabels"},{"attributes":{},"id":"3124","type":"PanTool"},{"attributes":{"axis":{"id":"3116"},"ticker":null},"id":"3119","type":"Grid"},{"attributes":{"overlay":{"id":"3130"}},"id":"3126","type":"BoxZoomTool"},{"attributes":{},"id":"3127","type":"SaveTool"},{"attributes":{},"id":"3114","type":"LinearScale"},{"attributes":{"axis_label":"y","formatter":{"id":"3146"},"major_label_policy":{"id":"3145"},"ticker":{"id":"3121"}},"id":"3120","type":"LinearAxis"},{"attributes":{"items":[{"id":"3154"}]},"id":"3153","type":"Legend"},{"attributes":{"text":"simple line example"},"id":"3106","type":"Title"},{"attributes":{},"id":"3110","type":"DataRange1d"},{"attributes":{"active_multi":null,"tools":[{"id":"3124"},{"id":"3125"},{"id":"3126"},{"id":"3127"},{"id":"3128"},{"id":"3129"}]},"id":"3131","type":"Toolbar"},{"attributes":{},"id":"3152","type":"Selection"},{"attributes":{},"id":"3125","type":"WheelZoomTool"},{"attributes":{},"id":"3128","type":"ResetTool"},{"attributes":{},"id":"3146","type":"BasicTickFormatter"},{"attributes":{"line_color":"#1f77b4","line_width":2,"x":{"field":"x"},"y":{"field":"y"}},"id":"3139","type":"Line"},{"attributes":{"line_alpha":0.1,"line_color":"#1f77b4","line_width":2,"x":{"field":"x"},"y":{"field":"y"}},"id":"3140","type":"Line"},{"attributes":{},"id":"3108","type":"DataRange1d"},{"attributes":{},"id":"3145","type":"AllLabels"},{"attributes":{"label":{"value":"Temp."},"renderers":[{"id":"3141"}]},"id":"3154","type":"LegendItem"}],"root_ids":["3105"]},"title":"Bokeh Application","version":"2.3.3"}}\';\n        var render_items = [{"docid":"c31e6567-ed76-4ba2-8ca1-3d74fe6710f7","root_ids":["3105"],"roots":{"3105":"96528c78-aea5-4535-9310-b624defedc39"}}];\n        root.Bokeh.embed.embed_items(docs_json, render_items);\n      \n        }\n        if (root.Bokeh !== undefined) {\n          embed_document(root);\n        } else {\n          var attempts = 0;\n          var timer = setInterval(function(root) {\n            if (root.Bokeh !== undefined) {\n              clearInterval(timer);\n              embed_document(root);\n            } else {\n              attempts++;\n              if (attempts > 100) {\n                clearInterval(timer);\n                console.log("Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing");\n              }\n            }\n          }, 10, root)\n        }\n      })(window);\n    });\n  };\n  if (document.readyState != "loading") fn();\n  else document.addEventListener("DOMContentLoaded", fn);\n})();'}
                    }
                    this.html= response.data.div
                    // 插入绘制script代码
                    let bokehRunScript = document.createElement('SCRIPT')
                    bokehRunScript.setAttribute('type', 'text/javascript')
                    let t = document.createTextNode(response.data.script)
                    bokehRunScript.appendChild(t)
                    document.body.appendChild(bokehRunScript)
                    // 绘制代码执行完后关闭等待画面
                    this.loading = false
                // })
            }
      }
  },
}
</script>
<style lang="scss" scoped>
.boken-pic_wrap {
    
}
</style>