2015-04-04 59 views
2

我需要在畫布上繪製多邊形,但我必須用鼠標點擊。例如:點擊一下鼠標點擊兩棵樹,然後點擊鼠標左鍵,最多點擊10次,然後點擊一行以填充所有點擊的點。純JS。如何用鼠標點擊畫布上的多邊形? Pure JS

function drawPolygon(position, sides, angle) { 
    var coordinates = [], 
     radius = Math.sqrt(Math.pow((dragStartLocation.x - position.x), 2) + Math.pow((dragStartLocation.y - position.y), 2)), 
     index = 0; 

    for (index = 0; index < sides; index++) { 
     coordinates.push({x: dragStartLocation.x + radius * Math.cos(angle), y: dragStartLocation.y - radius * Math.sin(angle)}); 
     angle += (2 * Math.PI)/sides; 
    } 

    context.beginPath(); 
    context.moveTo(coordinates[0].x, coordinates[0].y); 
    for (index = 1; index < sides; index++) { 
     context.lineTo(coordinates[index].x, coordinates[index].y); 
    } 

    context.closePath(); 
} 

回答

3

您只需添加一個mousedown事件處理程序。在mousedown中,將鼠標座標推入座標[]數組中。

var canvas=document.getElementById("canvas"); 
 
var context=canvas.getContext("2d"); 
 
var cw=canvas.width; 
 
var ch=canvas.height; 
 
function reOffset(){ 
 
    var BB=canvas.getBoundingClientRect(); 
 
    offsetX=BB.left; 
 
    offsetY=BB.top;   
 
} 
 
var offsetX,offsetY; 
 
reOffset(); 
 
window.onscroll=function(e){ reOffset(); } 
 

 
context.lineWidth=2; 
 
context.strokeStyle='blue'; 
 

 
var coordinates = []; 
 
var isDone=false; 
 

 
$('#done').click(function(){ 
 
    isDone=true; 
 
}); 
 

 
$("#canvas").mousedown(function(e){handleMouseDown(e);}); 
 

 
function handleMouseDown(e){ 
 
    if(isDone || coordinates.length>10){return;} 
 

 
    // tell the browser we're handling this event 
 
    e.preventDefault(); 
 
    e.stopPropagation(); 
 

 
    mouseX=parseInt(e.clientX-offsetX); 
 
    mouseY=parseInt(e.clientY-offsetY); 
 
    coordinates.push({x:mouseX,y:mouseY}); 
 
    drawPolygon(); 
 
} 
 

 
function drawPolygon(){ 
 
    context.clearRect(0,0,cw,ch); 
 
    context.beginPath(); 
 
    context.moveTo(coordinates[0].x, coordinates[0].y); 
 
    for(index=1; index<coordinates.length;index++) { 
 
    context.lineTo(coordinates[index].x, coordinates[index].y); 
 
    } 
 
    context.closePath(); 
 
    context.stroke(); 
 
}
body{ background-color: ivory; } 
 
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<h4>Click to assign polygon vertices</h4> 
 
<button id=done>Click when done assigning points</button> 
 
<br><canvas id="canvas" width=300 height=300></canvas>

+0

感謝支持我這工作得很好!另一個問題是否可以選擇我的多邊形並拖放(可拖動)? – 2015-04-04 18:26:49

+0

@coreid,很高興能幫到你。拖放確實是一個單獨的問題:-) – markE 2015-04-04 19:10:51

相關問題