10

我希望能够让我的用户选择他们上传的图像的特定多边形(点之间有曲线的 6-8 个顶点)区域 - 我该如何使用 HTML5 和 JS 来执行此操作?我发现的唯一库允许纯矩形选择: http: //odyniec.net/projects/imgareaselect/

4

2 回答 2

11

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

编辑:这是一个jsFiddle 演示。单击以选择原始图像上的点,然后按“生成”按钮生成裁剪版本。

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(); 
});
于 2012-10-27T13:33:03.620 回答
0

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

于 2012-10-27T20:38:55.790 回答