禁止在某些坐标上放置十字架

时间:2017-10-02 11:10:54

标签: javascript canvas

我的目标是将以下测试转发给少数人。练习是在图像上选择一个由十字表示的点。

使用.php我将存储每个参与者,并且对于新人的每个新显示,该人将看到历史性的选择。在该示例中,有一个signel参与坐标(570,80)

我的目的是禁止下一个参与者将他们的十字架放在坐标(570,80)+ - 10px(十字架的宽度)上。为了推断,完整的功能应该选择已经选择的坐标。怎么做?

<body>
<div style="width : 75%;margin : auto;">
    <canvas id="Canvas" width="954" height="267"></canvas>
</div>

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

// Map sprite
var mapSprite = new Image();
mapSprite.src = "image.png";
 var array_x = ["570"];
 var array_y = ["80"];





//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";

    setTimeout( function(){ 
    for (var i = 0; i < array_x.length; i++) {
    context.drawImage(cross, array_x[i], array_y[i], 10, 10);
    }}, 750 );


}
mapSprite.addEventListener('load', main);
</script>

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情:

var array_x = [570],
    array_y = [180]

function canBeMarked(x, y) {
  for (var i = 0; i < array_x.length; i++) {
    if (x > array_x[i] - 10 && x < array_x[i] + 10
     && y > array_y[i] - 10 && y < array_y[i] + 10) {
      return false;
     }
  }
  
  return true;
}

var x = 565,
    y = 189;
    
console.log(`[x: ${x}, y: ${y}] can be marked ? ${canBeMarked(x, y)}`);

x = 200;

console.log(`[x: ${x}, y: ${y}] can be marked ? ${canBeMarked(x, y)}`);