Javascript: 如何在多个位置绘制相同的多边形?

Javascript: how to draw same polygon in many positions?

我正在尝试创建一个简单的游戏模拟,用户可以在其中 select 一架飞机并四处移动。 我能够绘制一个平面并添加 4 个按钮来移动它。 但是,我不确定如何在随机位置创建 6 个完全相同的平面并绘制它们。 此外,用户必须能够select其中一架飞机并四处移动。

Jsfiddle:https://jsfiddle.net/fvtjzLhr/

HTML代码:

<canvas id="canvas" width="500" height="500"></canvas>
<br>
<button id="Left">Left</button>
<button id="Up">Up</button>
<button id="Down">Down</button>
<button id="Right">Right</button>

Javascript代码:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var poly=[ 20,0, 40,0, 50,15, 100,10, 130,30, 100,50, 50,45, 40,60, 20,60, 30,45, 20,40, 10,40, 0,45, 0,15, 10,20, 20,20, 30,15];

    var spaceship1 = {
        x: 0,
        y: 0,
        speed: 50,
        altitude: 360,
        id: 68,
        direction: 150
    }

    document.getElementById("Up").addEventListener("click", function(){
        spaceship1.y -= 30;
    });
    document.getElementById("Down").addEventListener("click", function(){
        spaceship1.y += 30;
    });
    document.getElementById("Left").addEventListener("click", function(){
        spaceship1.x -= 30;
    });
    document.getElementById("Right").addEventListener("click", function(){
        spaceship1.x += 30;
    });

    function renderSpaceship(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
        //ctx.fillStyle = '#D3D3D3';
        ctx.beginPath();
        ctx.moveTo(poly[0]+spaceship1.x, poly[1]+spaceship1.y);
        for( item=2 ; item < poly.length-1 ; item+=2 ){ctx.lineTo( poly[item]+spaceship1.x , poly[item+1]+spaceship1.y )}
        ctx.closePath();
        ctx.fill();
        ctx.font="17px Georgia";

        ctx.fillText("ID: "+spaceship1.id, spaceship1.x, 120+spaceship1.y);
        ctx.fillText("Altitude: "+spaceship1.altitude, spaceship1.x, 105+spaceship1.y);
        ctx.fillText("Speed: "+spaceship1.speed, spaceship1.x, 90+spaceship1.y);
        ctx.fillText("Direction: "+spaceship1.direction, spaceship1.x, 75+spaceship1.y);
    }

    function renderAll(){

        renderSpaceship();
    }

    setInterval(renderAll, 10);

它应该看起来像这样:

忽略背景。蓝色用于 selected 平面。

您将希望远离命名飞船并将它们存储在 Spaceship1 之类的变量中,一旦您需要开始实施许多飞船,这会导致大量重复代码。

为避免重复代码,请创建一个数组来容纳游戏中的每艘船。您的绘图函数应该遍历 ship 数组的每个元素并绘制它。

您可以创建一个名为 selectedShip 的变量,并在单击 up/down/right/left 按钮时更新该运送位置。要 'select' 另一艘船,只需监听您的 canvas 上的点击并检测对一艘船的点击。如果单击一艘船,请将您的 selectedShip 变量更新为被单击的变量。

对您的 fiddle 进行的一些编辑片段:

绘制时循环遍历每艘船

function renderSpaceships() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for(var i = 0; i < ships.length; i++) {
    var ship = ships[i];      
    ...
  }

添加一行创建船只的辅助函数

function addShip(x, y, id){
  ships.push({
    x: x,
    y: y,
    speed: 50,
    altitude: 320,
    id: id,
    direction: 150
  });
}

addShip(getRand(1, 400), getRand(1, 400), 68);

我没有为你的飞船添加任何点击监听器,你需要获取点击的坐标并检查你的数组中是否有任何飞船与点击的点重叠。然后更新selectedShip

New fiddle

这应该可以让您找到一个好的方向,在保持整洁的同时继续添加功能。祝你好运!