2017-08-11 54 views
1

我想在Konva中定义一个自定义形状,我尝试了下面的代码绘制一个矩形,我想记录点击它,但点击检测不起作用。为什么?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> 
+0

我觉得我读,有一个版本1.6.7 - 我相信已经有一些在这个旋转的自定义形状的事件检测的改进,也许这延伸到非也旋转。 –

回答

1

我不得不说,我不知道这个库的想法,但我很感兴趣,因为代码看起来很好。

在尝试使用常规形状的代码并看到事件处理函数工作后,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>

+0

谢谢。但我不明白为什么我必须打这个电话。该教程说,只需要调用中风和填充,这是我自己做的。 – cdarwin