2016-07-26 85 views
0

我使用cropper JS裁剪我的圖像。我能夠獲得畫布的寬度和高度,但是,需要知道裁剪圖像的座標(X和Y)。如何通過CropperJS獲得裁剪圖像的座標?

這裏是我的代碼 -

(function() { 


    //getting ratio 
    function getImageRatio(sourceCanvas) { 
    var canvas = document.createElement('canvas'); 
    var context = canvas.getContext('2d'); 
    var width = sourceCanvas.width; 
    var height = sourceCanvas.height; 



    canvas.width = width; 
    canvas.height = height; 


    context.beginPath(); 
    context.arc(width/2, height/2, Math.min(width, height)/2, 0, 2 * Math.PI); 
    context.strokeStyle = 'rgba(0,0,0,0)'; 
    context.stroke(); 
    context.clip(); 
    context.drawImage(sourceCanvas, 0, 0, width, height); 

    return canvas; 
    } 




    window.addEventListener('DOMContentLoaded', function() { 
    var image = document.getElementById('image'); 
    var button = document.getElementById('button'); 
    var result = document.getElementById('result'); 
    var croppable = false; 
    var cropper = new Cropper(image, { 
     aspectRatio: 1, 
     viewMode: 1, 
     built: function() { 
     croppable = true; 
     } 
    }); 

    button.onclick = function() { 
     var croppedCanvas; 
     var roundedCanvas; 
     var roundedImage; 

     if (!croppable) { 
     return; 
     } 

     // Crop 
     croppedCanvas = cropper.getCroppedCanvas(); 


     console.log(getImageRatio(croppedCanvas)); 

    }; 

    }); 

})(); 

任何想法,如何讓裁剪圖像座標,這樣我可以通過PHP裁剪這張圖片。

+0

我不知道爲什麼有些人總是有負面的頭腦!這裏放棄投票的原因是什麼? – tisuchi

回答

1

因此,如果我理解正確,您正在尋找methodgetData

的文件說,它會返回這些屬性:

x: the offset left of the cropped area 
y: the offset top of the cropped area 
width: the width of the cropped area 
height: the height of the cropped area 
rotate: the rotated degrees of the image 
scaleX: the scaling factor to apply on the abscissa of the image 
scaleY: the scaling factor to apply on the ordinate of the image 

雖然,我建議採取看看文檔的這一部分:具體在這​​個部分 https://github.com/fengyuanchen/cropper#getcroppedcanvasoptions

之後,您可以直接將畫布顯示爲圖像,或使用HTMLCanvasElement.toDataURL獲取數據URL,或使用HTMLCanvasElement.toBlob獲取ab如果瀏覽器支持這些API,則使用FormData將其上載到服務器。

如果您無法使用toBlob方法,因爲一些瀏覽器限制(你可以隨時添加填充工具),你可以使用toDataUrl在畫布(IE9 +)的圖像。並將其發送至已裁剪的後端服務。對於這一點,你將需要做這樣的事情:

var formData = new FormData(); 
formData.append('image', canvas.toDataURL()); 

可以在caniuse

希望你覺得它有用的檢查FORMDATA瀏覽器的支持!