Search code examples
javascriptecharts

How to change the line style of ECharts custom graph from solid to dashed or dotted


I created a custom graph using Apache ECharts to draw a vertical line from the input data. Following ECharts documentation and some online examples, I was able to draw the line and custom it with color or width as per the MWE below.

My question is how to configure the line style as dotted or dashed. I searched extensively but could not find any options or documentation on that.

const chart = echarts.init(document.getElementById("chart"));

const render = (_, api) => {
  const start1 = api.coord([api.value(0), api.value(1)]);
  const end1 = api.coord([api.value(0), api.value(2)]);
  const x1 = start1[0];
  const y1 = start1[1];
  const x2 = end1[0];
  const y2 = end1[1];
  const line = {
    type: "line",
    shape: {
      x1,
      y1,
      x2,
      y2
    },
    style: {
      stroke: "blue",
      lineWidth: 3
    }
  };

  return {
    type: "group",
    children: [line]
  };
};

const options = {
  xAxis: {
    min: 0,
    max: 2,
    interval: 1
  },
  yAxis: {
    min: 0,
    max: 4,
    interval: 1
  },
  series: [{
    type: "custom",
    data: [
      [1, 1, 3]
    ],
    renderItem: render
  }]
};
chart.setOption(options);
<!DOCTYPE html>
<html>

<head>
  <title>ECharts custom line</title>
  <meta charset="UTF-8" />
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js" integrity="sha256-TI0rIaxop+pDlHNVI6kDCFvmpxNYUnVH/SMjknZ/W0Y=" crossorigin="anonymous"></script>
</head>

<body>
  <div id="chart" style="width: 50%; height: 200px; position: absolute; top:0; left:0"></div>
</body>

</html>

MWE: https://codesandbox.io/s/echarts-custom-vertical-line-442cv


Solution

  • You can easily make custom dashed line in echarts. You need to pass lineDash to the graphic element object.

    lineDash is stroke-dasharray attribute of line defining the pattern of dashes and gaps. Pass the values of dashes and gaps in form of an number array.

    const render = (_, api) => {
      const start1 = api.coord([api.value(0), api.value(1)]);
      const end1 = api.coord([api.value(0), api.value(2)]);
      const x1 = start1[0];
      const y1 = start1[1];
      const x2 = end1[0];
      const y2 = end1[1];
      const line = {
        type: "line",
        shape: { x1, y1, x2, y2 },
        style: {
          stroke: "blue",
          lineWidth: 4,
          lineDash: [2] // put dash, gap values here
        }
      };
    
      return {
        type: "group",
        children: [line]
      };
    };