从中心显示十字

时间:2017-09-26 12:50:42

标签: javascript canvas

以下代码允许我单击图像(画布),具有坐标,并将十字准确放置在完成单击的位置。交叉的问题是,它将从角落(右下角)表示,我将在点击和十字之间有一个偏移,它不代表精确的坐标。换句话说,十字架的中心应该是延迟坐标的起源。

怎么做?

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 个答案:

答案 0 :(得分: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,这就是它上升的原因。在这种情况下,十字架将位于点击的中间位置。