How to change width and height of graphic 'rect' programmatically in Echarts (by implementing onClick event or make it resizable by dragging)

Viewed 89

I'm using latest echarts and trying to put a rectangle on the canvas using graphic option. We can set width and height of type: 'rect' by using Shape.width and Shape.height according to this documentation.

What I want to do is that I want to change that width and height of rectangle

  1. by clicking on it (by implementing onClick event)
  2. by dragging like in css 'resize' property to a div. Is this possible in echarts?

Here is the sample option code that I'm currently trying to implement. You can use it by replacing it here. The setter function setWidth() can change the value of width variable but Shape.width will not call getWidth() function again. There will not be a new render happening.

let width = 100;

function getWidth() {
  return width;
}

function setWidth(value) {
  width = value;
}

option = {
  graphic: {
    elements: [
      {
        type: 'rect',
        draggable: true,
        shape: {
          x: 0,
          y: 0,
          width: getWidth(),
          height: 100
        },
        style: {
          fill: 'red'
        },
        onclick: function(e) {
          setWidth(400)
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  }
};
1 Answers

Echarts options are usually not dynamic. Which means that if you change any option, you'll have to call yourChartName.setOption(option) (doc).

function setWidth(value) {
  option.graphic.elements[0].shape.width=value;
  myChart.setOption(option);
}
Related