如何使用JavaScript / jQuery选择图像的多边形区域?

时间:2012-08-26 06:24:47

标签: javascript jquery html5 html5-canvas

我希望能够让我的用户选择他们上传的图片的特定多边形(6-8个点之间有曲线的顶点)区域 - 我如何使用HTML5& amp; JS?我找到的唯一一个库允许纯粹的矩形选择:http://odyniec.net/projects/imgareaselect/

2 个答案:

答案 0 :(得分:10)

已经有一个库可以满足您的需求:polyclip.js, by Zoltan Dulac您可以构建一个允许用户选择点的UI,然后将数据提供给库,您就完成了。

编辑:这是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(); 
});

答案 1 :(得分:0)

您可以将图像加载到画布标签上,然后就可以在画布上完成您喜欢的所有绘图。