const layer = new Konva.Layer(); stage.add(layer);
// generate random shapes for (var i = 0; i < 10; i++) { const shape = new Konva.Circle({ x: Math.random() * stage.width(), y: Math.random() * stage.height(), radius: Math.random() * 30 + 5, fill: Konva.Util.getRandomColor(), draggable: true, // each shape MUSH have uniq name // so we can easily update the preview clone by name name: 'shape-' + i, }); layer.add(shape); }
// clone original layer, and disable all events on it // we will use "let" here, because we can redefine layer later let previewLayer = layer.clone({ listening: false }); previewStage.add(previewLayer);
functionupdatePreview(){ // we just need to update ALL nodes in the preview layer.children.forEach((shape) => { // find cloned node const clone = previewLayer.findOne('.' + shape.name()); // update its position from the original clone.position(shape.position()); }); }
stage.on('dragmove', updatePreview);
// add new shapes on double click or double tap stage.on('dblclick dbltap', () => { const shape = new Konva.Circle({ x: stage.getPointerPosition().x, y: stage.getPointerPosition().y, radius: Math.random() * 30 + 5, fill: Konva.Util.getRandomColor(), draggable: true, // each shape MUSH have uniq name // so we can easily update the preview clone by name name: 'shape-' + layer.children.length, }); layer.add(shape);
// remove all layer previewLayer.destroy(); // generate new one previewLayer = layer.clone({ listening: false }); previewStage.add(previewLayer); }); </script> </body> </html>
const layer = new Konva.Layer(); stage.add(layer);
// generate random shapes for (var i = 0; i < 10; i++) { const shape = new Konva.Circle({ x: Math.random() * stage.width(), y: Math.random() * stage.height(), radius: Math.random() * 30 + 5, fill: Konva.Util.getRandomColor(), draggable: true, // each shape MUSH have uniq name // so we can easily update the preview clone by name name: 'shape-' + i, }); layer.add(shape); }
// update preview only on dragend for performance stage.on('dragend', updatePreview);
// add new shapes on double click or double tap stage.on('dblclick dbltap', () => { const shape = new Konva.Circle({ x: stage.getPointerPosition().x, y: stage.getPointerPosition().y, radius: Math.random() * 30 + 5, fill: Konva.Util.getRandomColor(), draggable: true, // each shape MUSH have uniq name // so we can easily update the preview clone by name name: 'shape-' + layer.children.length, }); layer.add(shape);
updatePreview(); });
// show initial preview updatePreview(); </script> </body> </html>