在 Fabric.js 中克隆对象 [英] Cloning objects in Fabric.js

查看:117
本文介绍了在 Fabric.js 中克隆对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个简单的函数在 Fabric.js 的画布上克隆一个选定的对象.

I am cloning a selected object on a canvas in Fabric.js using a simple function.

function duplicateObj() {
  var obj = canvas.getActiveObject();
  var clone = fabric.util.object.clone(obj);
  clone.set({left: 100,top: 100});
  canvas.add(clone); 
}

这绝对没问题.现在,如果我使用该对象并且不再需要克隆并且我选择并删除它,那么对象、克隆和原始对象都将被删除.删除函数是:

That works absolutely fine. Now if I work with the object and the clone is not required anymore and I select and delete it, both objects, the clone and the original object are deleted. The delete function is:

function deleteObj() {
  var obj = canvas.getActiveObject();
  canvas.fxRemove(obj);
}

对象是相同的.有没有办法克隆对象并使克隆独立于原始对象?我试过这个:

The objects are the same. Is there are way to clone objects and make the clone independent of the of the original? I tried this:

function duplicateObj() {
  var obj = canvas.getActiveObject();
  var clone = fabric.util.object.clone(obj);
  clone.initialize();
  $.extend(clone, obj);
  fabric.util.object.extend(clone, obj);
  clone.set({left: 100,top: 100});
  canvas.add(clone); 
}

它可以工作,但是对象再次相同,如果我只使用初始化,我最终会得到一个现在设置了属性的对象.

It works, however the objects are the same again and if I only use initialize I am ending up with an object that has now properties set.

推荐答案

这里是解决方案

 var object = fabric.util.object.clone(canvas.getActiveObject());
    object.set("top", object.top+5);
    object.set("left", object.left+5);
     canvas.add(object);

这篇关于在 Fabric.js 中克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆