单击 Konva 形状不起作用

Konva shape on click doesn't work

我正在尝试在 Konva 中定义自定义形状,我尝试了以下绘制矩形的代码,我想记录点击次数,但点击检测不起作用。为什么?

不知道哪里错了

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
  <meta charset="utf-8">
  <title>Konva Custom Shape Demo</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #F0F0F0;
    }
  </style>
</head>
<body>
  <div id="container"></div>
  <script>
    var stage = new Konva.Stage({
      container: 'container',
      width: 300,
      height: 300
    });
    var layer = new Konva.Layer();
    var rect = new Konva.Shape({
      sceneFunc: function(ctx) {
            ctx.beginPath();
            ctx.lineWidth = 2;
            ctx.fillStyle = "white";
            ctx.strokeStyle = "black";
            ctx.rect(10, 10, 100, 100);
            ctx.fill();
            ctx.stroke();
            ctx.closePath();
    }});

    rect.on("click", function() {
        console.log("click");
    });
    layer.add(rect);
    stage.add(layer);
  </script>
</body>
</html>

我不得不说我对这个库一无所知,但我很感兴趣,因为代码看起来不错。

在用常规形状尝​​试你的代码并看到事件处理程序工作后,Konva 的事件系统如何检测自定义形状的点击肯定是个问题。

检查 the official tutorial on custom shapes 并添加一个事件侦听器(有效)让我进行了并排比较,发现唯一的区别是您的代码缺少此方法调用:

// Konva specific method
context.fillStrokeShape(this);

添加该方法调用后,您的事件处理程序可以正常工作。

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
  <meta charset="utf-8">
  <title>Konva Custom Shape Demo</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #F0F0F0;
    }
  </style>
</head>
<body>
  <div id="container"></div>
  <script>
    var stage = new Konva.Stage({
      container: 'container',
      width: 300,
      height: 300
    });
    var layer = new Konva.Layer();
    var rect = new Konva.Shape({
      sceneFunc: function(ctx) {
            ctx.beginPath();
            ctx.lineWidth = 2;
            ctx.fillStyle = "white";
            ctx.strokeStyle = "black";
            ctx.rect(10, 10, 100, 100);
            ctx.fill();
            ctx.stroke();
            ctx.closePath();
            ctx.fillStrokeShape(this);
    }});

    rect.on("click", function() {
        console.log("click");
    });
    layer.add(rect);
    stage.add(layer);
  </script>
</body>
</html>