Рисование или удаление части Drag Drop Image Konva JS Image - PullRequest
0 голосов
/ 07 августа 2020

Теперь я использовал Konva JS для своего веб-приложения, которое создает составное изображение путем перетаскивания, что хорошо работает.

Теперь я попытался последовать совету о том, как выполнять рисование или стирание с помощью применение внешнего компонента холста, как предложено в This Konva JS article и This stackoverflow answer. До сих пор я все еще не могу выполнить рисование или стирание изображения перетаскивания, как я хочу.

Вот мой код перетаскивания с внешней переменной холста.

 var lastPointerPosition; // variable to detect mouse poiint 
    var mode = 'norm'; // set mode for brush and eraser
    var BrushColorString  = '#F3CDA6'; // skin color 
    var BrushColorVal = hexToRgb(BrushColorString); 
    var BrushRadius = 5;
var stage = new Konva.Stage({
        container: 'MyCanvas',
        width: width,
        height: height
    });
    var layer = new Konva.Layer();
    stage.add(layer);

  // what is url of dragging element?
var itemURL = '';
document.getElementById('ImageDirectory').addEventListener('dragstart', function(e) {
      itemURL = e.target.src;
});

    var con = stage.container();
con.addEventListener('drop', function(e) {
        e.preventDefault();
        // now we need to find pointer position
        // we can't use stage.getPointerPosition() here, because that event
        // is not registered by Konva.Stage
        // we can register it manually:
        stage.setPointersPositions(e);
        var ImageDragDrop = new Image();  ;  
        var PaintCanvas = document.createElement('canvas'); // external canvas 
        var PaintContext;
        if(PaintCanvas.getContext) {
            PaintContext = PaintCanvas.getContext('2d');
            PaintContext.fillStyle = BrushColorString;
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = BrushRadius;
            ImageDragDrop.src = itemURL; 
            PaintCanvas.width = ImageDragDrop.width;
            PaintCanvas.height = ImageDragDrop.height;
            indexCentral = ((ImageDragDrop.width*ImageDragDrop.height*0.5) + ImageDragDrop.width*0.5)*4;
            PaintContext.drawImage(ImageDragDrop, 0, 0);
        }
        .....
        var image = new Konva.Image({
            name: 'FaceImg',
            id: 'Image' + ImageNumber,
            image: PaintCanvas, // critical 
            draggable: true,
            
        });  // the way to set attribute name  for find algorithm of Konva.Image

   ......

});

Вот событие мыши переменной изображения Konva для рисования или стирания

image.on('mouseenter', function () {
                
            if(mode === 'brush')
            {
                stage.container().style.cursor = 'default';
                image.draggable(false);
            } else if(mode === 'brush')
            {
                stage.container().style.cursor = 'default';
                image.draggable(false);
            } else if(mode === 'floodfill')
            {
                stage.container().style.cursor = 'pointer';
                image.draggable(false);
            }
        });

        image.on('mouseleave', function () {
            stage.container().style.cursor = 'default';
             
        });

        image.on('mousedown touchstart', function () {
            stage.container().style.cursor = 'pointer';
                // need to set a condtion for painting and erasing 
            lastPointerPosition = stage.getPointerPosition();
            
        });
    image.on('mousemove touchmove', function () {
        
            // need to set a condtion for painting and erasing 
        if (!isPaint) {
            return;
        }
        // the real mechanic for painting 
        if(mode === 'brush') {
            image.draggable(false);
            stage.container().style.cursor = 'default';
            PaintContext.globalCompositeOperation = 'source-over';  
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = BrushRadius;               
     
             
        } else if(mode === 'eraser'){
            image.draggable(false);
            stage.container().style.cursor = 'default';
            PaintContext.globalCompositeOperation = 'destination-out'; 
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = BrushRadius;       
                  
        } else if(mode === 'floodfill'){
            image.draggable(false);
            stage.container().style.cursor = 'pointer';
            PaintContext.globalCompositeOperation = 'color';     
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = 1;     
            // call flood fill function here 
           
        }
        if (mode === 'norm') {
            stage.container().style.cursor = 'move';
            PaintContext.globalCompositeOperation = "source-atop";  // restore default comp
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = BrushRadius;       
               
        }
        PaintContext.beginPath();

        var localPos = {
            x: lastPointerPosition.x - image.x(),
            y: lastPointerPosition.y - image.y()
        };
        PaintContext.moveTo(localPos.x, localPos.y);
        var pos = stage.getPointerPosition();
        localPos = {
            x: pos.x - image.x(),
            y: pos.y - image.y()
        };
        PaintContext.lineTo(localPos.x, localPos.y);
        PaintContext.closePath();
        PaintContext.stroke();

        lastPointerPosition = pos;
        layer.batchDraw();
    });   
    image.on('mouseup touchend', function () {
        stage.container().style.cursor = 'pointer'; 
             // need to set a condtion for painting and erasing 
        isPaint = false;
         
     });    

Я даже добавляю код для рисования и стирания в событиях мыши сцены, но он все равно работает

stage.on('mousedown touchstart', (e) => {
        // do nothing if we mousedown on eny shape
        if (e.target !== stage) {
          return;
        }
        .....
         
        

// dealing with paint 
            
            if(mode === 'brush')
        {
            isPaint = true;
            image.draggable(false);
            lastPointerPosition = stage.getPointerPosition();
        } else if(mode === 'brush')
        {
            isPaint = true;
            image.draggable(false)
            lastPointerPosition = stage.getPointerPosition();
        } else if(mode === 'floodfill')
        {
            isPaint = true;
        

    image.draggable(false)
            lastPointerPosition = stage.getPointerPosition();
        }
         
        layer.draw();
      });
      // Mouae move event of stage
      stage.on('mousemove touchmove', () => {
       ....
        // DEALING WITH PAINT
        if (!isPaint) {
          return;
        }
        if(mode === 'brush') {
            stage.container().style.cursor = 'default';
            PaintContext.globalCompositeOperation = 'source-over';   
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = BrushRadius;   
                 
        } else if(mode === 'eraser'){
            stage.container().style.cursor = 'default';
            PaintContext.globalCompositeOperation = 'destination-out';    
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = BrushRadius;   
        } else if(mode === 'floodfill'){
            stage.container().style.cursor = 'pointer';
            PaintContext.globalCompositeOperation = 'color';
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = 1; 
        }
        if (mode === 'norm') {
            stage.container().style.cursor = 'move';
            PaintContext.globalCompositeOperation = 'source-atop';    
            PaintContext.strokeStyle = BrushColorString;
            PaintContext.lineJoin = 'round';
            PaintContext.lineWidth = BrushRadius;               
        }
        PaintContext.beginPath();
        var localPos = { 
                x: lastPointerPosition.x - image.x(), 
                y: lastPointerPosition.y -image.y() 
        };
        PaintContext.lineTo(localPos.x, localPos.y);
        PaintContext.closePath();
        PaintContext.stroke();

        lastPointerPosition = pos;
            
        
        layer.batchDraw();
      });
      // Mouse Up 
      stage.on('mouseup touchend', () => {
        isPaint = false;
      ......
});

Я сделали что-то не так на моем внешнем холсте, поэтому моя программа все еще не может выполнить paintbru sh или стереть компонент Konva Image? Пожалуйста, помогите мне. Выполнение рисования или стирания на изображении перетаскиванием с помощью Konva JS

...