2016-07-25 48 views
1

我已在畫布上繪製圖像。如何使用基於鼠標點擊來裁剪選定的矩形

我希望用戶點擊畫布來裁剪圖像的一部分。

我該怎麼做?

+1

這是很清楚你的問題是什麼。請嘗試描述您的問題更詳細。特別是第一句話很難理解。 – smoes

+0

您是否要裁剪圖像?你在畫布上有一個圖像,然後你想要用戶在畫布上定義一個矩形區域,畫布被裁剪,然後該圖像可能會被上傳?以下鏈接顯示如何使用畫布進行圖像裁剪:http://tympanus.net/codrops/2014/10/30/resizing-cropping-images-canvas/ –

回答

0

這裏有一個輪廓,讓你開始:

  • 繪製圖像到畫布上

    var canvas=document.getElementById('myCanvas'); 
    canvas.drawImage(yourImageObject,0,0); 
    
  • 監聽mousedown事件。

    canvas.onmousedown=function(e){handleMouseDown(e);}; 
    
  • 已在左上角[x0,y0]和右下角[x1,y1]角落裏,他們要裁剪和記錄那些2個鼠標位置的用戶點擊。

  • 裁剪矩形的定義如下:

    var x=x0; 
    var y=y0; 
    var width=x1-x0; 
    var height=y1-y0; 
    
  • 創建第二畫布元件和尺寸使其剪切大小:

    var secondCanvas = document.createElement('canvas'); 
    secondCanvas.width = width; 
    secondCanvas.height = height; 
    document.body.appendChile(secondCanvas); 
    
  • 使用drawImage裁剪版本來繪製從第一個畫布到第二個畫布的裁剪矩形

    secondCanvas.drawImage(canvas, 
        x,y,width,height, // clip just the cropping rectangle from the first canvas 
        0,0,width,height // draw just the cropped part onto the first canvas 
    ); 
    

用戶選擇的圖像部分現在位於第二個畫布上。

如果你想第二畫布轉換爲圖像對象,你可以這樣做:

var img=new Image(); 
img.onload=start; 
img.src=secondCanvas.toDataURL(); 
function start(){ 
    // at this point, img contains the cropped portion of the original image 
} 
相關問題