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

时间:2017-11-20 17:42:51

标签: javascript graphics polygon

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

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);

看起来应该是这样的: enter image description here

忽略背景。蓝色适用于所选平面。

1 个答案:

答案 0 :(得分:2)

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

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

您可以创建一个名为selectedShip的变量,并在每次单击向上/向下/向右/向左按钮时更新该变量。要选择&#39;另一艘船只是听你的画布点击并检测船上的点击。如果点击了一艘船,请将selectedShip变量更新为点击的变量。

对你的小提琴编辑的一些片段:

绘制时遍历每艘船

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

这应该让你指出一个好的方向,即在保持整洁的同时不断添加功能。祝你好运!

相关问题