2012-08-26 180 views
9

我希望能夠讓我的用戶選擇他們上傳的圖像中特定的多邊形(點之間有曲線的6-8頂點)區域 - 我該如何使用HTML5 & JS來做這件事?我發現的唯一庫允許純矩形選區:http://odyniec.net/projects/imgareaselect/如何使用JavaScript/jQuery選擇圖像的多邊形區域?

+0

您可能必須親自編寫它,方法是在用戶單擊的點之間畫線。這不是非常困難,但有十幾行非常針對你的問題。這可能取決於你想要用你的多邊形做什麼。 –

回答

10

有已,做你需要什麼零件庫:polyclip.js, by Zoltan Dulac您可以構建一個用戶界面,允許用戶選擇點,然後將數據反饋到庫和你'重做。

編輯:這是一個jsFiddle demonstration。單擊以選擇原始圖像上的點,然後按生成按鈕生成裁剪版本。

HTML

<div id="mainContent"> 
    <div id="canvasDiv"> 
     <br/> 
     <button id="generate" type="button">Generate 
     </button> 
    </div> 
    <h1>Result:</h1> 
    <div class="clipParent" style="float:left;"> 
    </div> 
</div> 

JS

var canvasDiv = document.getElementById('canvasDiv'); 
canvas = document.createElement('canvas'); 
canvas.setAttribute('width', 500); 
canvas.setAttribute('height', 500); 
canvas.setAttribute('id', 'canvas'); 
$(canvasDiv).prepend(canvas); 
if(typeof G_vmlCanvasManager != 'undefined') { 
    canvas = G_vmlCanvasManager.initElement(canvas); 
} 

var context = canvas.getContext('2d'); 
var imageObj = new Image(); 

imageObj.onload = function() { 
    $(canvas).attr({width : this.width, height: this.height}); 
    context.drawImage(imageObj,0,0); 
}; 
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; 

var clickX = new Array(); 
var clickY = new Array(); 
var clickDrag = new Array(); 
var paint; 

function addClick(x, y, dragging) 
{ 
    clickX.push(x); 
    clickY.push(y); 
    clickDrag.push(dragging); 
} 

function redraw(){ 
    canvas.width = canvas.width; // Clears the canvas 
    context.drawImage(imageObj,0,0); 

    context.strokeStyle = "#df4b26"; 
    context.lineJoin = "round"; 
    context.lineWidth = 5; 

    for(var i=0; i < clickX.length; i++) 
    { 
    context.beginPath(); 
    context.arc(clickX[i], clickY[i], 3, 0, 2 * Math.PI, false); 
    context.fillStyle = '#ffffff'; 
    context.fill(); 
    context.lineWidth = 5; 
    context.stroke(); 
    } 
} 

$('#canvas').click(function(e){ 
    var mouseX = e.pageX - this.offsetLeft; 
    var mouseY = e.pageY - this.offsetTop; 

    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop); 
    redraw(); 
}); 

$('#generate').click(function(){ 
    $(".clipParent").empty(); 
    $(".clipParent").prepend('<img src="http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg" id="genimg" />'); 
    var arr = []; 
    for(var i=0; i < clickX.length; i++){ 
     arr.push(clickX[i]); 
     arr.push(clickY[i]); 
    } 
    $("#genimg")[0].setAttribute("data-polyclip",arr.join(", ")); 
    clickX=[]; 
    clickY=[]; 
    redraw(); 
    polyClip.init(); 
}); 
+0

非常感謝這麼多! – user1198133

0

你可以到一個畫布標記加載圖像,然後你可以做所有你喜歡的畫布上繪製。