2017-09-26 46 views
1

下面的代碼允許我點擊一個圖像(畫布),獲得座標,並在完成點擊的位置放置一個十字。十字架的問題,它將從角落(右下角)表示,並且我將在點擊和十字架之間產生偏移,這些偏移並不代表確切的座標。換句話說,十字的中心應該是放棄座標的原點。從中心顯示十字線

如何做到這一點?

var canvas = document.getElementById('Canvas'); 
 
var context = canvas.getContext("2d"); 
 

 
// Map sprite 
 
var mapSprite = new Image(); 
 
mapSprite.src = "image.png"; 
 

 
//Declare Marker sprite 
 
var Marker = function() { 
 
    this.Sprite = new Image(); 
 
    this.Sprite.src = "cross.png" 
 
    this.Width = 10; 
 
    this.Height = 10; 
 
    this.XPos = 0; 
 
    this.YPos = 0; 
 
} 
 

 
var Markers = new Array(); 
 

 
var mouseClicked = function (mouse) { 
 
    // Get corrent mouse coords 
 
    var rect = canvas.getBoundingClientRect(); 
 
    var mouseXPos = Math.round(mouse.x - rect.left); 
 
    var mouseYPos = Math.round(mouse.y - rect.top); 
 

 
    console.log("Marker added"); 
 

 
    // Move the marker when placed to a better location 
 
    var marker = new Marker(); 
 
    marker.XPos = mouseXPos - (marker.Width/2); 
 
    marker.YPos = mouseYPos - marker.Height; 
 
    marker.YPosNew = marker.YPos; 
 
    Markers.push(marker); 
 

 
    // Draw marker 
 
    context.drawImage(Markers[0].Sprite, Markers[0].XPos, Markers[0].YPos, Markers[0].Width, Markers[0].Height); 
 
    // Calculate postion text 
 
    var markerText = Markers[0].XPos + ", " + Markers[0].YPosNew; 
 

 

 
    // disable pointer after 1s 
 
    setTimeout(function(){ 
 
    document.getElementById('Canvas').style.cursor="not-allowed"; } , 1000); 
 
} 
 

 
// Add mouse click event listener to canvas 
 
canvas.addEventListener("mousedown", mouseClicked, false); 
 

 
var main = function() { 
 
    draw(); 
 
}; 
 

 
var draw = function() { 
 
    // Clear Canvas 
 
    context.fillStyle = "#000"; 
 
    context.fillRect(0, 0, canvas.width, canvas.height); 
 

 
    // Draw diagramme 
 
    context.drawImage(mapSprite, 0, 0, 954, 267); 
 
    //draw all precedent cross 
 
    cross = new Image(); 
 
    cross.src = "cross.png"; 
 

 
} 
 
mapSprite.addEventListener('load', main);
<div style="width : 75%;margin : auto;"> 
 
    <canvas id="Canvas" width="954" height="267"></canvas> 
 
</div>

回答

1
var marker = new Marker(); 
marker.XPos = mouseXPos - (marker.Width/2); 
marker.YPos = mouseYPos - (marker.Height/2); 
marker.YPosNew = marker.YPos; 
Markers.push(marker); 

改變你的標記的Ypos,這就是爲什麼它往上走。在這種情況下,十字會定位在點擊的中間位置。