我在画布上有一个矩形。还有两个按钮可将矩形从红色更改为绿色。
如果我从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>
最佳答案
不知道这是否是问题,但是由于fabricjs我也无法做到这一点,所以我不得不在fabricjs上添加事件。
fabric.util.addListener(canvas, 'contextmenu', function (e) {
your code here
}