在paper.js中无法编辑ImportJson路径后

时间:2018-04-12 13:10:15

标签: javascript paperjs

以下是用于导出和导入纸张js布局的代码。

$('#btnSave').click(function () {
     var json = paper.project.activeLayer.exportJSON();
     localStorage.setItem('oncjson', json);
     alert('Data has been save successfully;');
});

$('#btnGet').click(function () {
     var json = localStorage.getItem('oncjson');
     paper.project.activeLayer.importJSON(json);
     paper.project.view.update();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-full.js"></script>

它按照预期加载数据但是一旦导入完成,我就无法改变或拖动路径中的段。就像在画布上渲染的硬编码设计一样。

任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:1)

根据您的描述,我认为问题在于您期望事件处理程序将与序列化数据一起导入。
不幸的是,情况并非如此,因为自定义回调几乎无法序列化(有关更多详细信息,请参见此issue)。

这是在两个分离的画布中模拟导出/导入的示例。
您可以看到,导入后,我们需要手动附加事件处理程序。

// create one scope per canvas
var scope1 = new paper.PaperScope();
scope1.setup(document.getElementById('canvas1'));
var scope2 = new paper.PaperScope();
scope2.setup(document.getElementById('canvas2'));

// draw a circle in canvas 1
new paper.Path.Circle({
  center: scope1.view.center,
  radius: 50,
  fillColor: 'orange',
  parent: scope1.project.activeLayer,
  // name it so we can easily find it in hierarchy
  name: 'circle'
});

// draw instructions
new paper.PointText({
  content: 'Drag the circle around',
  justification: 'center',
  point: scope1.view.center.subtract(0, 80),
  parent: scope1.project.activeLayer
});

// bind custom drag handler to circle (using its name to find it)
scope1.project.activeLayer.children['circle'].onMouseDrag = customDragHandler;

// export canvas 1 content
var json = scope1.project.exportJSON();

// import it into canvas 2
scope2.project.importJSON(json);

// we need to manually attach event handler for canvas 2 as it wasn't serialized
scope2.project.activeLayer.children['circle'].onMouseDrag = customDragHandler;

// this position the item under the mouse pointer when it is dragged
function customDragHandler(event) {
  this.position = event.point;
}
html,
body {
  margin: 0;
  overflow: hidden;
  height: 100%;
}

main {
  display: flex;
  height: 100vh;
}

canvas {
  flex: 1;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-core.min.js"></script>

<main>
  <canvas id="canvas1" resize></canvas>
  <canvas id="canvas2" resize></canvas>
</main>