javascript - Is there a way to get the difference between 2 points by click and hold with the mouse on a line on chart.js? - Sta

admin2025-04-30  0

I have seen so many custom charts and I would like to know how to modify them too.

Is there a way on such a chart chart.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="/[email protected]/dist/chart.umd.js"></script>

    <!-- this 2 are for zoom plugin -->
    <script src="/[email protected]"></script>
    <script src="/[email protected]/dist/chartjs-plugin-zoom.min.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .chart-container {
            position: relative;
            width: 90%;
            height: 200px;
            background-color: black;
            color: white;
        }
        
        #chart {
            width: 100%;
        }
        </style>
    </head>
<body>
    <div class="chart-container" id="chart-container" style="text-align:center;">
        <canvas id="chart" style="display: inline-block;"></canvas>
    </div>


    <script>
        const ctx = document.getElementById('chart').getContext('2d');

        let data = [];
        
        function generateRandomData(numPoints) {
            let currentDate = new Date();

            for (let i = 0; i < numPoints; i++) {
                const rand_plus_or_minus = Math.round(Math.random()) * 2 - 1;
                
                const y = Math.random() * 100 + 50;

                new_date = parseInt(currentDate.getTime()/1000)*1000 + i * 24 * 60 * 60 * 1000;

                data.push({
                    x: new_date,
                    y: y,
                });
            }
        }

        generateRandomData(50);

    

        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                datasets: [
                    {
                        type: 'line',
                        label: 'Dataset 1',
                        data: data,
                        borderColor: chartLineColor,
                        backgroundColor: chartLineColor,
                        borderWidth: 1,
                        fill: false,
                        pointStyle: 'circle',
                        hoverRadius: 5,
                    },
                ],
            },
            options: {
                    animation: false,
                    responsive: true,
                    maintainAspectRatio: false,
                elements: {
                    point:{
                        radius: 0
                    },
                },
                plugins: {
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        enabled: true,
                    },


                        zoom: { //plugin
                            zoom: {
                                wheel: {
                                    enabled: true,
                                },
                                pinch: {
                                    enabled: true
                                },
                                mode: 'x',
                                limits: {
                                    x: {min: 0, max: 100},
                                },
                                onZoomStart: ({ chart, event, point }) => {
                                    document.getElementById('button_reset_mainchart_zoom').style = "display: block;";
                                },
                            },
                        },



                },
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                scales: {
                    x: {
                        type: 'linear',
                        title: {
                            display: true,
                            text: 'X Axis',
                        },
                        offset: false,
                        //offset: true,
                    },
                    y: {
                        title: {
                            display: true,
                            text: 'Y Axis',
                        },
                    },
                },
            },
        });
    
    
        function chartLineColor (firstvalue, lastvalue) {
       firstvalue = data[0].y;
       lastvalue = data[data.length - 1].y;
                if (firstvalue < lastvalue) {
                    return 'green';
                } else if (firstvalue > lastvalue) {
                    return 'red';
                } else {
                    return 'grey';
                }
            }
      

    
        </script>
    
    
            <script>
                resetZoomBtn = (chart) => {
                    chart.resetZoom()
                };
                </script>

                <button id="button_reset_mainchart_zoom" type="button" class="btn btn-secondary" onclick="resetZoomBtn(chart); this.style = 'display: none;';">Reset Zoom</button>

    </body>
</html>

Working sample:

/

to get the difference between two points by clicking on an area of ​​the graph with the mouse and dragging the mouse to the desired point of the canvas?

Look at the image to understand the result I would like to achieve:

I have seen so many custom charts and I would like to know how to modify them too.

Is there a way on such a chart chart.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.js"></script>

    <!-- this 2 are for zoom plugin -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-zoom.min.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .chart-container {
            position: relative;
            width: 90%;
            height: 200px;
            background-color: black;
            color: white;
        }
        
        #chart {
            width: 100%;
        }
        </style>
    </head>
<body>
    <div class="chart-container" id="chart-container" style="text-align:center;">
        <canvas id="chart" style="display: inline-block;"></canvas>
    </div>


    <script>
        const ctx = document.getElementById('chart').getContext('2d');

        let data = [];
        
        function generateRandomData(numPoints) {
            let currentDate = new Date();

            for (let i = 0; i < numPoints; i++) {
                const rand_plus_or_minus = Math.round(Math.random()) * 2 - 1;
                
                const y = Math.random() * 100 + 50;

                new_date = parseInt(currentDate.getTime()/1000)*1000 + i * 24 * 60 * 60 * 1000;

                data.push({
                    x: new_date,
                    y: y,
                });
            }
        }

        generateRandomData(50);

    

        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                datasets: [
                    {
                        type: 'line',
                        label: 'Dataset 1',
                        data: data,
                        borderColor: chartLineColor,
                        backgroundColor: chartLineColor,
                        borderWidth: 1,
                        fill: false,
                        pointStyle: 'circle',
                        hoverRadius: 5,
                    },
                ],
            },
            options: {
                    animation: false,
                    responsive: true,
                    maintainAspectRatio: false,
                elements: {
                    point:{
                        radius: 0
                    },
                },
                plugins: {
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        enabled: true,
                    },


                        zoom: { //plugin
                            zoom: {
                                wheel: {
                                    enabled: true,
                                },
                                pinch: {
                                    enabled: true
                                },
                                mode: 'x',
                                limits: {
                                    x: {min: 0, max: 100},
                                },
                                onZoomStart: ({ chart, event, point }) => {
                                    document.getElementById('button_reset_mainchart_zoom').style = "display: block;";
                                },
                            },
                        },



                },
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                scales: {
                    x: {
                        type: 'linear',
                        title: {
                            display: true,
                            text: 'X Axis',
                        },
                        offset: false,
                        //offset: true,
                    },
                    y: {
                        title: {
                            display: true,
                            text: 'Y Axis',
                        },
                    },
                },
            },
        });
    
    
        function chartLineColor (firstvalue, lastvalue) {
       firstvalue = data[0].y;
       lastvalue = data[data.length - 1].y;
                if (firstvalue < lastvalue) {
                    return 'green';
                } else if (firstvalue > lastvalue) {
                    return 'red';
                } else {
                    return 'grey';
                }
            }
      

    
        </script>
    
    
            <script>
                resetZoomBtn = (chart) => {
                    chart.resetZoom()
                };
                </script>

                <button id="button_reset_mainchart_zoom" type="button" class="btn btn-secondary" onclick="resetZoomBtn(chart); this.style = 'display: none;';">Reset Zoom</button>

    </body>
</html>

Working sample:

https://jsfiddle.net/d31xmgep/

to get the difference between two points by clicking on an area of ​​the graph with the mouse and dragging the mouse to the desired point of the canvas?

Look at the image to understand the result I would like to achieve:

Share Improve this question edited Jan 5 at 1:07 user27160653 asked Jan 4 at 22:36 user27160653user27160653 18110 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

i did make an solution that calculates the deiffrence between two points by clicking but this solution does not have the drag functionality or the style of display that you wanted but i hope this piece of code helps you alot:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.js"></script>

    <!-- this 2 are for zoom plugins -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-zoom.min.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;

            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .chart-container {
            position: relative;
            width: 90%;
            height: 200px;
            background-color: black;
            color: white;
        }
        
        #chart {
            width: 100%;
        }
        </style>
    </head>
<body>
  <div class="chart-container" id="chart-container" style="text-align:center;">
    <canvas id="chart" style="display: inline-block;"></canvas>
  </div>
  <div class="result">Click on two points to subtract their Y values.</div>
  <script>
    const ctx = document.getElementById('chart').getContext('2d');
    let data = [];
    function generateRandomData(numPoints) {
      let currentDate = new Date();
      for (let i = 0; i < numPoints; i++) {
        const rand_plus_or_minus = Math.round(Math.random()) * 2 - 1;
        const y = Number((Math.random() * 100 + 50).toFixed(2));
        new_date = parseInt(currentDate.getTime()/1000)*1000 + i * 24 * 60 * 60 * 1000;
        data.push({
          x: new_date,
          y: y,
        });
      }
    }
    generateRandomData(50);
    const chart = new Chart(ctx, {
      type: 'line',
      data: {
        datasets: [
          {
            type: 'line',
            label: 'Dataset',
            data: data,
            borderColor: chartLineColor,
            backgroundColor: chartLineColor,
            borderWidth: 1,
            fill: false,
            pointStyle: 'circle',
            hoverRadius: 5,
          },
        ],
      },
      options: {
        animation: false,
        responsive: true,
        maintainAspectRatio: false,
        elements: {
          point:{
            radius: 0
          },
        },
        onClick: (event, elements) => {
          // Handle point clicks
          if (elements.length) {
            const firstPointIndex = elements[0].index;
            // If no point has been clicked yet this is the first point
            // so put it in the variable.
            if (typeof window.selectedPointIndex === 'undefined') {
              window.selectedPointIndex = firstPointIndex;
              document.querySelector('.result').textContent = `Selected point: ${data[firstPointIndex].x} (Y = ${data[firstPointIndex].y})`;

            } else if (typeof window.selectedPointIndex === 'number') {
              const firstY = data[window.selectedPointIndex].y;
              const secondY = data[firstPointIndex].y;
              var result = Number((secondY - firstY).toFixed(2))

              // Display result
              document.querySelector('.result').textContent = `Difference: ${secondY} - ${firstY} = ${result}`;

              // Clear the selected point
              delete window.selectedPointIndex;
            }
          }
        },
        plugins: {
          tooltip: {
            mode: 'index',
            intersect: false,
            enabled: true,
          },
          zoom: { //plugin
            zoom: {
              wheel: {
                enabled: true,
              },
              pinch: {
                enabled: true
              },
              mode: 'x',
              limits: {
                x: {min: 0, max: 100},
              },
              onZoomStart: ({ chart, event, point }) => {
                document.getElementById('button_reset_mainchart_zoom').style = "display: block;";
              },
            },
          },
        },
        interaction: {
          mode: 'index',
          intersect: false,
        },
        scales: {
          x: {
            type: 'linear',
            title: {
              display: true,
              text: 'X Axis',
            },
            offset: false,
            //offset: true,
          },
          y: {
            title: {
              display: true,
              text: 'Y Axis',
            },
          },
        },
      },
    });
    function chartLineColor (firstvalue, lastvalue) {
      firstvalue = data[0].y;
      lastvalue = data[data.length - 1].y;
      if (firstvalue < lastvalue) {
        return 'green';
      } else if (firstvalue > lastvalue) {
        return 'red';
      } else {
        return 'grey';
      }
    }
  </script>
  <script>
    resetZoomBtn = (chart) => {
      chart.resetZoom()
    };
  </script>
  <button id="button_reset_mainchart_zoom" type="button" class="btn btn-secondary" onclick="resetZoomBtn(chart); this.style = 'display: none;';">Reset Zoom</button>
  </body>
</html>

i might edit the answer so it fills all the needs of your question if needed

转载请注明原文地址:http://anycun.com/QandA/1746025221a91509.html