preface

Echarts sets the ROAM property toscaleortrueTo turn on the mouse zoom effect. But when you zoom in, you’ll notice that the font doesn’t change with the zoom. As shown in the figure below. The problem with this article is getting text to scale as Echarts scales.

The difficulty problem

Mouse events supported by Echarts include ‘click’, ‘dblclick’, ‘mousedown’, ‘Mousemove’, ‘mouseup’, ‘mouseover’, ‘mouseout’, ‘GlobalOut’, ‘ContextMenu’. Echarts scaling is triggered by mouse scrolling, and Echarts does not support mousewheel. Registering mouseWheel directly with echartsInstance does not work.

usegetZr()Register and cancelmousewheelThe event

I don’t know what getZr is, but Baidu found a function that supports event registration and cancellation. A clear partner can leave a message to share.

Echartsinstance.getzr ().on(‘eventName’, callback)

Cancel event: echartsinstance.getzr ().off(‘eventName’, callback)

Native Echarts charts to achieve font scaling

The fontsize of the label is dynamically changed according to the zoom value

// Cancel events before registering
hotWordCloud.getZr().off("mousewheel")
// Set text (zoom text)
hotWordCloud.getZr().on("mousewheel".function () {
    let option2 = hotWordCloud.getOption();
    if(option2.series[0]) {let zoom = option2.series[0].zoom;
        wordsArr.forEach(item= > {
            item.label.fontSize = item.label.fontSize * zoom;
            item.symbolSize = item.symbolSize * zoom;
            return item;
        })
        option.series[0].force.edgeLength = option.series[0].force.edgeLength * zoom
        option.series[0].force.repulsion = option.series[0].force.repulsion * zoom

        option.series[0].data = wordsArr hotWordCloud.setOption(option); }});Copy the code

React-for-echarts component diagrams for font scaling

Due to the react – for – echarts echarts encapsulation, getZr functions are encapsulated in the enclosing refs. MyEcharts. GetEchartsInstance (.) _api inside.

<ReactEcharts ref="myEcharts" className="echarts-warpper" option={this.state.option}/>

let hotWordCloud = this.refs.myEcharts.getEchartsInstance()._api;
hotWordCloud.getZr().off("mousewheel")
// Set text (zoom text)
hotWordCloud.getZr().on("mousewheel".() = > {
    let option2 = hotWordCloud.getOption();
    if(option2.series[0]) {let zoom = option2.series[0].zoom;
        option2.series[0].data.forEach(item= > {
            item.label.normal.fontSize = item.label.normal.fontSize * zoom;
            item.symbolSize = item.symbolSize * zoom;
            return item;
        })
        letoption = {... this.state.option};//@ts-ignore
        option.series[0].force.edgeLength *=  zoom
        //@ts-ignore
        option.series[0].force.repulsion *= zoom
        //@ts-ignore
        option.series[0].data = option2.series[0].data
        this.setState({option})
        //@ts-ignore
        this.refs.myEcharts.rerender()
    }
});
Copy the code

Take a look at the effect