chartjs-plugin-zoom не работает в автономном режиме javascript .js - PullRequest
0 голосов
/ 14 декабря 2018

Я работаю в автономном режиме и использую импорт chartjs из зеркала пряжи: Chart.js 2.7.2 chartjs-plugin-zoom 0.6.6 hammerjs 2.0.8 момент 2.23.0

и я импортировал их в свой файл .js как import 'chartjs-plugin-zoom', импортировал 'hammerjs', импортировал 'moment', импортировал {Chart} из 'chart.js'.

Я такжевсе мои файлы в комплекте, и я могу видеть зависимости в комплекте.

В узловых модулях моего проекта работают образцы увеличения, а также resetZoom();, но когда я запускаю их в своем проекте, я получаю ошибку:

Я не могу увеличить мойдиаграмма с прокруткой мыши.

У меня есть пункт меню, который устанавливает:

options:{
  zoom:{
    enabled:true,
    mode:'y'
  },
  pan:{
    enabled:true,
    mode:'y'
   }
  }

Я вижу, как это работает, так что теоретически это должно работать правильно ??Что не так ??

Также я попытался вручную добавить:

options:{
  zoom:{
    enabled:true,
    mode:'y'
  },
  pan:{
    enabled:true,
    mode:'y'
  }
}

, когда я добавляю диаграмму и все еще ничего ...

    import "moment"
    import { Chart } from "chart.js"
    import "hammerjs"
    import "chartjs-plugin-annotation"
    import "chartjs-plugin-zoom"


    /// The main component of web-plots. The plot ties together sever chart
    /// objects from the chart.js module.
    export const Plot = class {

    constructor(props) {
        // initialize props
        this.props = props
        //global to keep track of rawlrv attributes from manager.js
        this.globlrv = null
        this.desirable= null
        // Initialize state variables
        this.charts = [] // maps ids to a chart
        this.root = document.createElement('ray-plot') // parent node of plot

        // constructs charts and applies properties
        const { plotData } = props
        plotData.forEach(chartData => this.addChart(chartData))
        props.plotData = this.charts.map(chart => {
            return {
                type: chart.type,
                data: chart.data,
                options: chart.options,
            }
        })

        props.backgroundColor.map((color, index) => this.changeBackgroundColor(index, color))

        this.title = props.plotTitle
    }

    set title(title) {
        this.charts[0].options.title.display = title? true: false
        this.charts[0].options.title.text = title
    }


    get title() {
        return this.charts[0].options.title.text
    }

    getProps(){
        return this.props
    }

    changeZoomPanEnabled(chartId, enabled){

        const chart = this.charts[chartId]
        chart.options.zoom.enabled = enabled
        chart.options.pan.enabled = enabled

    }

    changeZoom(chartId, mode){
        this.charts[chartId].options.zoom.mode = mode
        this.charts[chartId].options.pan.mode = mode
    }

    changeBackgroundColor(chartId, color){
        this.charts[chartId]
            .chart
            .canvas
            .parentNode
            .style
            .backgroundColor = color
    }

    changeGridLineColor(chartId, color){
        const scales = this.charts[chartId].scales
        Object.keys(scales)
            .map(key => scales[key])
            .forEach(axis => {
                axis.options.gridLines.color = color
                axis.originalOptions.gridLines.color = color
            })
    }

    changeGridLineDisplay(chartId, display){
        const scales = this.charts[chartId].scales
        Object.keys(scales)
            .map(key => scales[key])
            .forEach(axis => {
                axis.options.gridLines.display = display
                axis.originalOptions.gridLines.display = display
            })
    }

    changeFontColor(chartId, color){
        const chart = this.charts[chartId]
        const scales = chart.scales

        Object.keys(scales)
            .map(key => scales[key])
            .forEach(axis => {
                axis.originalOptions.scaleLabel.fontColor = color
                axis.originalOptions.ticks.fontColor = color
                axis.options.scaleLabel.fontColor = color
                axis.options.ticks.fontColor = color
            })
        chart.options.title.fontColor = color
        chart.options.legend.labels.fontColor = color
    }

    getXAxisMinimum(chartId){
        return this.charts[chartId]
            .options
            .scales
            .xAxes[0]
            .time
            .min
    }

    setXAxisMinimum(chartId, minimum){
        this.charts[chartId]
            .options
            .scales
            .xAxes[0]
            .time
            .min = minimum
    }

    getXAxisMaximum(chartId){
        return this.charts[chartId]
            .options
            .scales
            .xAxes[0]
            .time
            .max
    }

    setXAxisMaximum(chartId, maximum){
        this.charts[chartId]
            .options
            .scales
            .xAxes[0]
            .time
            .max = maximum
    }

    setXAxisLabel(chartId, dataset, title){
        const axis = this.charts[chartId].scales["x-axis-" + dataset]

        const scaleLabel = axis.options.scaleLabel
        scaleLabel.display = title? true:false
        scaleLabel.labelString = title

        const originalScaleLabel = axis.originalOptions.scaleLabel
        originalScaleLabel.display = title? true:false
        originalScaleLabel.labelString = title
    }

    setYAxisLabel(chartId, axisId, title){
        const axis = this.charts[chartId].scales[axisId]

        const scaleLabel = axis.options.scaleLabel
        scaleLabel.display = title? true:false
        scaleLabel.labelString = title

        const originalScaleLabel = axis.originalOptions.scaleLabel
        originalScaleLabel.display = title? true:false
        originalScaleLabel.labelString = title
    }

    getData(chartId, datasetId){
        return this.charts[chartId]
            .data
            .datasets[datasetId]
            .data
    }

    setData(chartId, datasetId, data){
        this.charts[chartId]
            .data
            .datasets[datasetId]
            .data = data
    }

    setPointColor(chartId, datasetId, pointColor){
        this.charts[chartId]
            .data
            .datasets[datasetId]
            .pointBorderColor = pointColor
    }

    getPointColor(chartId, datasetId){
        const dataset = this.charts[chartId]
            .data
            .datasets[datasetId]

        if(dataset.pointBorderColor === undefined){
            dataset.pointBorderColor = []
        }
        return dataset.pointBorderColor
    }

    getChartDatasetInfo(){
        return this.charts.map((chart, index) => [index, chart.data.datasets.length])
    }

    getThreshCallback(chartId, rawLrv){
            var plotOpt = this.charts[chartId].options
            var loRed = parseInt(rawLrv.lowerRedLimit)
            var loYellow = parseInt(rawLrv.lowerYellowLimit)
            var hiRed = parseInt(rawLrv.upperRedLimit)
            var hiYellow = parseInt(rawLrv.upperYellowLimit)
            plotOpt.annotation.annotations = []
            var min = parseInt(this.charts[chartId].scales["y-axis-0"].min)
            var max = parseInt(this.charts[chartId].scales["y-axis-0"].max)



    }

    update(chartId, lrv = null) {
        if(chartId === undefined){
            for(var x = 0; x<this.charts.length; x++){
                this.charts[x].update()
                    }
                }
            else {
            this.charts[chartId].update()

        }

    }

    changeLineSymbol(chartId, datasetId, symbol) {
        const dataset = this.charts[chartId]
            .data
            .datasets[datasetId]

        if(symbol){
            dataset.pointRadius = 6
            dataset.pointStyle = symbol
        } else {
            dataset.pointRadius = 0
        }
    }

    changeLineStyle(chartId, datasetId, style) {
        this.charts[chartId]
            .data
            .datasets[datasetId]
            .borderDash = style
    }

    getLineStyle(chartId, datasetId) {
        return this.charts[chartId]
            .data
            .datasets[datasetId]
            .borderDash
    }

    changeLineColor(chartId, datasetId, color) {
        const dataset = this
            .charts[chartId]
            .data
            .datasets[datasetId]

        dataset.borderColor = color.line
        dataset.backgroundColor = color.fill
    }

    addChart(chartData) {
        const ctx = document.createElement('canvas')
        const container = document.createElement('ray-chart')
        container.appendChild(ctx)


        var ds = chartData.data.datasets
        for(var a = 0;a<ds.length;a++){
        ds[a].borderColor ="rgba(0,255,0,1)"
        }


        const chart = new Chart (ctx, {
            type: chartData.type,
            data: chartData.data,
            options: chartData.options,
        })
        chart.options.annotation= {}



        //default annotations off
        chart.options.annotation.display = false



        container.addEventListener("dblclick", () => {
            if(chart.options.pan.enabled || chart.options.zoom.enabled){
                chart.resetZoom()
            }
        }, false)




        this.charts.push(chart)
        this.root.appendChild(container)
        this.layout()
    }

    // Remove a chart from the stack of charts in the plot.
    removeChart(chartId) {
        const chart = this.charts[chartId]
        this.charts.splice(chartId, 1)
        this.root.removeChild(chart.chart.canvas.parentNode)
        this.layout()
    }

    resetZoom(chartId) {
        const chart = this.charts[chartId]
        if(chart.options.pan.enabled || chart.options.zoom.enabled){
            chart.resetZoom()
        }
    }

    alarm(chartId, togle){
    const chart = this.charts[chartId]
    if(togle =='off'){
    chart.options.annotation = {
    display:false
    }
    chart.update()
    chart.options.annotation = {
    display:false
    }
    }else{
    chart.options.annotation.display = true
    if(this.globlrv !== null){
        this.getThreshCallback(chartId, this.globlrv)
        chart.update()
        this.getThreshCallback(chartId, this.globlrv)
    }
    }
    }

    // Calculates the new height of each chart in the plot and applies
    // the new style.
    layout() {
        const size = 1/this.root.childNodes.length * 100
        Array.from(this.root.childNodes).forEach((node) => {
            node.style.height = size + "%"
        })
    }

    staticPage() {
        const root = document.createElement("div")
        root.style.backgroundColor = this.root.style.backgroundColor
        root.style.position = "absolute"
        this.charts.map(chart => {
                let img = document.createElement("img")
                img.setAttribute("src", chart.toBase64Image())
                img.style.display = "block"
                img.style.backgroundColor = chart.chart.canvas.parentNode.style.backgroundColor
                return img
            })
            .forEach(item => root.appendChild(item))

        const body = document.createElement("body")
        body.appendChild(root)
        const html = document.createElement("html")
        html.appendChild(document.createElement("head"))
        html.appendChild(body)
        return html
    }
}

1 Ответ

0 голосов
/ 15 июля 2019

Вам потребуется добавить плагин в качестве родителя для масштабирования и панорамирования, если вы используете скрипты плагинов.

Это выглядит так.Найти более подробную информацию здесь

plugins: {
      zoom: {
            pan: {
                enabled: true,
                mode: 'xy'
                },
            zoom: {
                enabled: true,
                mode: 'xy'
                }
             },



<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.3"></script>

Пример кода

window.onload = function () {
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myBar = new Chart(ctx, {
        type: 'line',
        data: barChartData,
        options: {
            // Elements options apply to all of the options unless overridden in a dataset
            // In this case, we are setting the border of each bar to be 2px wide and green
            elements: {
                rectangle: {
                    borderWidth: 0,
                    borderSkipped: 'bottom'
                }
            },
            responsive: true,
            legend: {
                display: false,
                position: 'top',
            },
            title: {
                display: true,
                text: 'LOADS'
            },

            plugins: {
                zoom: {
                    pan: {
                        enabled: true,
                        mode: 'xy'
                    },
                    zoom: {
                        enabled: true,
                        mode: 'xy'
                    }
                }
            },

            scales: {
                yAxes: [
                    {
                        stacked: true,
                        gridLines: {
                            display: true
                        },
                        scaleLabel: {
                            display: false
                        },
                        ticks: {
                            display: true
                        }
                    }
                ],
                xAxes: [{
                    stacked: true,
                    scaleLabel: {
                        display: false
                    },
                    ticks: {
                        display: true,
                        min: 'January-17',
                        max: 'December-17'
                    }
                }]
            }
        }
    });
};


var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var randomScalingFactor = function () {
    return (Math.random() > 0.5 ? 1.0 : 1.0) * Math.round(Math.random() * 10000);
};
var randomColorFactor = function () {
    return Math.round(Math.random() * 255);
};
var randomColor = function () {
    return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)';
};

var barChartData = {
    labels: ["January-16", "February-16", "March-16", "April-16", "May-16", "June-16", "July-16", "August-16", "September-16", "October-16", "November-16", "December-16", "January-17", "February-17", "March-17", "April-17", "May-17", "June-17", "July-17", "August-17", "September-17", "October-17", "November-17", "December-17"],
    datasets: [{
        label: 'Credit Card',
        backgroundColor: "rgba(133,169,69,0.9)",
        data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
    }, {
        label: 'Cash',
        backgroundColor: "rgba(151,187,205,0.5)",
        data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
    }]

};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...