📜  图表 js 渲染打印 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:06.932000             🧑  作者: Mango

代码示例1
/*Vue & Vue-Chart.JS
I have resonsive layout and the charts would scale with parent container.
When a user would print the chart I tried resizing it with JS in the 
beforeprint and afterprint window listeners, This caused a shift in the chart
position in the print preview. If you need to re-render/resize the chart it
is easier to convert the canvas to a image. */

//DoughnutChart.js ()
// I will only show the key parts
import { Doughnut } from 'vue-chartjs'
export default {
    extends: Doughnut
      props: {
        ...
          //chartId is a prop for vue-chart.js.
          //Give it a unique id if you have multiple charts on the page
          chartId: {
            type: String,
            required: true
        },
          ...
    },
     methods: {
         beforePrintResizeCharts() {
          //Getting the Canvas and parent node
          //Create a data URL for the canvas
            const CHART_CANVAS = this.$el.children.namedItem(this.chartId);
            const CANVAS_PARENT = CHART_CANVAS.parentElement;
            const CANVAS_DATA_URL = CHART_CANVAS.toDataURL();

              //Create image and add canvas data URL to image as source
            let printable_image = document.createElement('IMG');

            printable_image.id = `${this.chartId}_image_copy`;
            printable_image.src = CANVAS_DATA_URL;
            printable_image.style.width = '100%';
            printable_image.style.height = 'auto';

              //Hide the canvas chart
            CHART_CANVAS.style.display = 'none';
            CANVAS_PARENT.append(printable_image);
        },
        afterPrintResizeCharts() {
           //Getting the Canvas and image version of canvas chart
            const CHART_CANVAS = this.$el.children.namedItem(this.chartId);
            const printable_image = this.$el.children.namedItem(this.chartId + "_image_copy");
            
              //remove image of canvas chart
            printable_image.parentElement.removeChild(printable_image);
          
            //Restore canvas visibility
            CHART_CANVAS.style.display = 'block';
        },
     },
     mounted() {
         //After renderChart method in mounted
         this.renderChart(chart_data, chart_options);

         //Add the beforeprint and afterprint event listners and use the vue methods
         //as the callbacks.
         window.addEventListener('beforeprint', this.beforePrintResizeCharts);
         window.addEventListener('afterprint', this.afterPrintResizeCharts);
     }
}