如何从右键单击元素(fabric.js)

时间:2017-04-21 22:07:55

标签: javascript html5-canvas fabricjs

我在画布上有一个矩形。还有两个按钮可以将矩形从红色变为绿色。 如果我从mouse:down事件中获取元素它可以工作但是从contextmenu(右键单击)它不会。我错过了什么?

var canvas = new fabric.Canvas('c');

var objectname ='';

function createObject() {
 
    objectname  = prompt("Enter name : ", "");     
  

  var rect1 = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'green',
  width: 20,
  height: 20,
  id :objectname+"Rect"      
  });
    
    canvas.add(rect1);
    alert(rect1.id);  
} 
                      
document.getElementById("CreateAnObject").onclick = createObject;


fabric.Canvas.prototype.getItemByName1 = function(name) {
  var object = null,
      objects = this.getObjects();

  for (var i = 0, len = this.size(); i < len; i++) {
    if (objects[i].id && objects[i].id === name) {
      object = objects[i];
      break;
    }
  }

  return object;
};

function ObjectRed(){
   canvas.getItemByName1(objectname).setFill('Red');
   canvas.renderAll(); 
}
document.getElementById("ObjectRed").onclick = ObjectRed;

function ObjectGreen(){    
   canvas.getItemByName1 (objectname).setFill('Green');
   canvas.renderAll(); 
}
document.getElementById("ObjectGreen").onclick = ObjectGreen;

canvas.on('mouse:down', function(e) {
    objectname  = e.target.id;
  });

document.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
   objectname  = e.target.id;
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Custom!</title> 
</head>
<body>  
    <input type="button" id="ObjectRed" value="Problem" /><br/>
    <input type="button" id="ObjectGreen" value="Okay" /><br/> 
     <input type="button" id="CreateAnObject" value="CreateAnObject"/><br/> 
    <canvas id="c" width="1010" height="550" style="border:1px solid #000000;">  
 <script src="fabric.min.js"></script>
 <script src="createObject.js"></script> 
</body>
</html>

1 个答案:

答案 0 :(得分:0)

不确定是否是问题,但由于fabricjs我也做不到,所以我不得不在fabricjs添加事件。

fabric.util.addListener(canvas, 'contextmenu', function (e) {
  your code here
}