如何使 AmCharts 4 图例具有可切换的复选框

How to make AmCharts 4 legend having a toggleable checkbox

我正在尝试使用复选框图例设置 AmCharts 4 图表。

我已经为每个图例设置了背景图片,但找不到在打开和关闭图例项时切换该图片的方法。

        // add legend
        this.chart.legend = new am4charts.Legend();
        this.chart.legend.useDefaultMarker = true;

        // Remove square from marker template
        const marker = this.chart.legend.markers.template;
        marker.disposeChildren();

        // Add custom image instead
        const checkbox = marker.createChild(am4core.Image);
        checkbox.width = 40;
        checkbox.height = 40;
        checkbox.verticalCenter = "top";
        checkbox.horizontalCenter = "left";
        checkbox.adapter.add("href", (href: any, target: any) => {
            if(!target.dataItem.dataContext.isHidden) {
                return "http://cdn.onlinewebfonts.com/svg/img_207414.png";
            }
            else {
                return '';
            }
        });

我会保留原始标记正方形并将其调整为:

  1. 保持现有的交互行为,
  2. 形成复选框的边界框(注意:他的复选框图像 没有边界框)。

切换图例项时,其对象更改为 the "active" State。因此,与其尝试在 Imagehref 上使用适配器,不如为其创建一个 "active" State,其中 opacity 设置为 0.

省略适配器(并调整图像的大小 and/or 标记的正方形以使其匹配),这是附加代码:

  const markerColumn = marker.children.getIndex(0);

  // Optionally straighten out the square
  markerColumn.cornerRadius(0, 0, 0, 0);
  // Hide the square
  markerColumn.defaultState.properties.fillOpacity = 0;
  // Form the bounding box
  markerColumn.defaultState.properties.strokeWidth = 1;
  markerColumn.defaultState.properties.stroke = am4core.color("#000");
  markerColumn.defaultState.properties.strokeOpacity = 1;

  // After your checkbox code... again, omit/comment out the href adapter
  checkbox.href = "https://cdn.onlinewebfonts.com/svg/img_207414.png";
  checkbox.dx = 1;
  checkbox.dy = 1;

  const checkboxActiveState = checkbox.states.create("active");
  checkboxActiveState.properties.opacity = 0;

演示:

https://codepen.io/team/amcharts/pen/89495edd36c6bf90d57262e2d7b9c182

截图: