ChartJS滚动速度过快

ig9co6j1  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(188)

我有一个简单的网页,它将某个邮政编码的天气数据加载到chart.js图表中:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
    <meta charset="UTF-8" />
    <title>Weather Chart</title>
    <link rel="icon" href="/logo.png">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/1.2.1/chartjs-plugin-zoom.js"></script>

    <style>
        #myChart {
            width: 100%;
            max-width: 600px;
        }
    </style>
</head>
<body>

    <div><b>Input Zip Code:</b></div>
    <input type="text" id="zipCodeInput">
    <br>
    <button id="zipCodeSubmit">Ok</button>
    <br><br><br>
    <div id="cityDisplay"></div>
    <div id="currentTime"></div>
    <div id="canvasDiv">
        <canvas id="weatherChart"></canvas>
    </div>

    <script>
    // Execute a function when the user presses a key on the keyboard
    document.getElementById('zipCodeInput').addEventListener("keypress", function(event) {
        // If the user presses the "Enter" key on the keyboard
        if (event.key == "Enter") {
            // Cancel the default action, if needed
            event.preventDefault();
            // Trigger the button element with a click
            document.getElementById("zipCodeSubmit").click();
        }
    });

    function printFancyTime(dateObj) {
        return dateObj.toLocaleDateString() + " " + dateObj.toLocaleTimeString();
    }

    // https://bobbyhadz.com/blog/javascript-get-hours-and-minutes-from-date
    function getHour(dateObject) {
        return dateObject.toLocaleTimeString('en-US', {
            // en-US can be set to 'default' to use user's browser settings
            hour: '2-digit',
            minute: '2-digit',
        });
    }

    function getUserPosition() {
        function showPosition(position) {
            var posLat = position.coords.latitude;
            var posLng = position.coords.longitude;
            var accuracy = position.coords.accuracy;
        }
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
    }

    var OWMkey = "dbf262da490678e53bec10704ce4032d";

    document.getElementById('zipCodeSubmit').addEventListener('click', function() {
        var geoUrl = `https://api.openweathermap.org/geo/1.0/zip?zip=${$('#zipCodeInput').val()},US&units=imperial&appid=${OWMkey}`;
        $.getJSON(geoUrl, function(data) {
            initChart(data.lat, data.lon);
            //document.getElementById('cityDisplay').innerHTML = data.name;

            var getWDGLocationUrl = `https://api.weather.gov/points/${data.lat},${data.lon}`;
            $.getJSON(getWDGLocationUrl, function(data) {
                var cityname = data.properties.relativeLocation.properties.city + ", " + data.properties.relativeLocation.properties.state;
                document.getElementById('cityDisplay').innerHTML = cityname;
                document.getElementById('currentTime').innerHTML = printFancyTime(new Date());
            })
        })
    })

    function initChart(lat, lng) {
        //document.getElementById('canvasDiv').innerHTML = '<canvas id="myChart"></canvas>';
        if (Chart.getChart("weatherChart")) {
            Chart.getChart("weatherChart").destroy();
        }

        var ziplat = lat
        var ziplon = lng

        var tempArr = [];
        var cloudArr = [];
        var cloudPercentArr = [];
        var tsArr = [];
        var dataUrl = `https://api.openweathermap.org/data/2.5/onecall?lat=${ziplat}&lon=${ziplon}&units=imperial&appid=${OWMkey}`;
        $.getJSON(dataUrl, function(data) {
            console.log(data.hourly[0])
            for (var x = 0; x < 20; x++) {
                var ts = data.hourly[x].dt;
                tsArr.push(getHour(new Date(ts * 1000)));
                //console.log(data.hourly[x].temp)
                tempArr.push(data.hourly[x].temp);
                //console.log(printFancyTime(new Date(ts * 1000)))
                cloudArr.push(data.hourly[x].clouds);
                cloudPercentArr.push(data.hourly[x].clouds);
            }

            var minTemp = Math.floor(Math.min(...tempArr) / 10) * 10;
            var maxTemp = Math.ceil(Math.max(...tempArr) / 10) * 10;

            for (var w = 0; w < cloudArr.length; w++) {
                // https://stackoverflow.com/questions/11107227/how-to-get-a-percentage-from-a-range#comment59972657_11107254
                cloudArr[w] = ((cloudArr[w] / 100) * (maxTemp - minTemp)) + minTemp
            }

            var weatherChart = new Chart("weatherChart", {
                type: "line",
                data: {
                    labels: tsArr,
                    datasets: [{
                        label: "temp",
                        fill: false,
                        lineTension: 0,
                        backgroundColor: "rgba(0, 0, 255, 1.0)",
                        borderColor: "rgba(0, 0, 255, 0.1)",
                        data: tempArr
                    }, {
                        label: "clouds",
                        fill: true,
                        lineTension: 0,
                        backgroundColor: "rgba(130, 130, 130, 0.2)",
                        borderColor: "rgba(130, 130, 130, 0.5)",
                        pointBackgroundColor: 'rgba(130, 130, 130, 1)',
                        data: cloudArr,
                    }]
                },
                options: {
                    plugins: {
                        legend: {display: false},
                        zoom: {
                            zoom: {
                                wheel: {
                                    enabled: true,
                                },
                                pinch: {
                                    enabled: true
                                },
                                mode: 'x',
                            },
                            pan: {
                                enabled: true,
                                mode: 'x'
                            },
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    var label = context.parsed.y || '';
                                    var id = context.dataset.label;
                                    var dataIndex = context.dataIndex;

                                    if (id == 'clouds') {
                                        return `${cloudPercentArr[dataIndex]} %`
                                    } else if (id == 'temp') {
                                        return label += ' F'
                                    }
                                }
                            }
                        }
                    },
                }
            });
        })
    }
    </script>

</body>
</html>

正如你所看到的,如果你用两个手指滚动图表,它会非常快。有人知道我可以放慢缩放速度的方法吗?
我已经试过speedsensitivity选项,但是到目前为止它们都不起作用。也许我把它们放在错误的位置了?有人能帮帮我吗?

cyvaqqii

cyvaqqii1#

您可以添加和设置:

zoom: { enabled: true, drag: false, mode: "x", speed: 0.1, sensitivity: 0.01 },

Chart.defaults.global.animation.duration = [ms];

相关问题