echarts 仪表板指针点击事件

 var gauge = document.getElementById('gauge');
    var myChart = echarts.init(gauge);
    var { width, height } = getComputedStyle(gauge);
    // 计算出中心点位置
    var x = parseInt(width.slice(0, -2), 0) / 2;
    var y = parseInt(height.slice(0, -2), 0) / 2;
    var maxAngle = 180;
    var minAngle = 0;
    var maxValue = 100;
    var dataRatio = maxValue / maxAngle;
    var option = {
        animation: false,
        series: [{
            name: '业务指标',
            type: 'gauge',
            startAngle: maxAngle, 
            endAngle: minAngle, 
            detail: {formatter:'{value}%'},
            data: [{value: 50, name: '完成率'}]
        }]
    };
    myChart.setOption(option);
    
    function changeValue(event) {
        var x2 = event.offsetX;
        var y2 = event.offsetY;
        // 当前点击位置的角度.
        var currentAngle = Math.atan2(y - y2, x - x2) * 180 / Math.PI;
        // 边界处理
        if (currentAngle < minAngle || currentAngle > maxAngle) {
            let _angle = Math.abs(currentAngle);
            if (_angle > 90) {
                currentAngle = maxAngle;
            } else {
                currentAngle = minAngle;
            }
        }
        // 转换回数据值, 这里就是实际的值, 默认保留2位小数, 需要传给后台.
        let value = (currentAngle * dataRatio).toFixed(2);
        option.series[0].data[0].value = value;
        myChart.setOption(option);
    }

    myChart._zr.on('mousedown', function(event) {
        changeValue(event);
        myChart._zr.on('mousemove', changeValue);
    });
    myChart._zr.on('mouseup', function(event) {
        myChart._zr.off('mousemove', changeValue);
    });
posted @ 2021-05-31 14:21  剑小新  阅读(826)  评论(0编辑  收藏  举报