按下左键或右键时,我可以添加什么代码来使图像旋转?

时间:2019-01-08 05:19:23

标签: javascript html5-canvas image-rotation

当我按下键盘上的向左或向右按​​钮时,我希望我的“ GamePiece”在其中心点旋转。我是一名学习者,正在学校里学习javascript。我看过类似的文章,但发现它们确实令人困惑。由于我是在晚上写这篇文章,因此我可能不会在接下来的18小时内回复。

JavaScript:

var myGamePiece;
var myBackground;


function startGame() {
    myGameArea.start();
    myGamePiece = new component(30, 30, "GamePiece.png", 10, 500, "image");
    myBackground = new component(656, 270, "PLACE IMAGE HERE", 0, 0, "image");
    var button = document.getElementById("Play");
    button.style.display = "none";  
}

var myGameArea = {
    canvas : document.getElementById("myCanvas"),
    start : function() {
        this.canvas.width = 1300;
        this.canvas.height = 600;
        this.canvas.style.position = "absolute";
        this.canvas.style.top = "267px";
        this.canvas.style.left = "303px";
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        window.addEventListener('keydown', function (e) {
            myGameArea.keys = (myGameArea.keys || []);
            myGameArea.keys[e.keyCode] = (e.type === "keydown");
        });
        window.addEventListener('keyup', function (e) {
            myGameArea.keys[e.keyCode] = (e.type === "keydown");            
        });
    }, 
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
};

function component(width, height, color, x, y, type) {
    this.type = type;
    if (type === "image") {
        this.image = new Image();
        this.image.src = color;
    }
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;    
    this.update = function() {
        context = myGameArea.context;
        if (type === "image") {
            context.drawImage(this.image, 
                this.x, 
                this.y,
                this.width, this.height);
        } else {
            context.fillStyle = color;
            context.fillRect(this.x, this.y, this.width, this.height);
        }
    };
    this.newPos = function() {
        this.x += this.speedX;
        this.y += this.speedY;        
    };
}


function updateGameArea() {
    myGameArea.clear();
    myGamePiece.speedX = 0;
    myGamePiece.speedY = 0;    
    if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -1; }
    if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 1; }
    if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; }
    if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; }
    myGamePiece.newPos();    
    myGamePiece.update();
    myBackground.newPos();
    myBackground.update();
}  

我希望在按下按键时使圆形图像(“ GamePiece”)从其中心旋转。

对不起,我不清楚 我希望球像在地面上滚动一样旋转。这是一个二维平台。 Like This one我希望只要按住按钮就可以使球滚动

2 个答案:

答案 0 :(得分:0)

如果您将画布视为可以移动的纸,但是笔是固定的,则可以更轻松地可视化旋转图像的工作方式。您将整个画布移动到要旋转的点(图像的坐标),将画布旋转所需的旋转量,将笔向后拉动并向上拉动图像大小的一半(因此中心在旋转的点上),然后正常绘制图像。现在,当您将画布/纸张重置为其原始位置时,图像仍会以您想要的位置和旋转度绘制在画布上。

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

var square1 = {
  x: 50,
  y: 50,
  w: 50,
  h: 25,
  rotation: -25
};
var square2 = {
  x: 150,
  y: 50,
  w: 50,
  h: 50,
  rotation: 45
};

drawSquare(square1);
drawSquare(square2);

function drawSquare(square) {
  ctx.save(); //saves the original state of the canvas
  ctx.translate(square.x, square.y); //moves the canvas to the object's point of origin
  ctx.rotate(square.rotation * Math.PI / 180); //rotates the canvas the desired amount
  ctx.fillRect(-(square.w / 2), -(square.h / 2), square.w, square.h); //draws the object
  ctx.restore(); //restores the canvas to its original position
}
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

对于在按键上旋转,它的工作方式与您的移动相同。为每个对象存储一个值以进行旋转,然后根据所需的旋转速度递增该值。

答案 1 :(得分:0)

您实际上只需要使用addEventListener来监听keydown上的document事件。如果触发keydown事件,则事件处理程序应检查所按下的键是否为向右箭头按钮-您可以通过访问e.keyCode并检查其是否等于39来实现这一点-如果是的话,设置图像style.transform属性使其旋转。

e是传递给事件处理程序的参数(浏览器会为您传递e)-它包含有关您正在侦听的事件的元数据负载。

以下是我上面描述的示例:

const imgEl = document.querySelector('#imgEl');
let offset = 0;

document.addEventListener('keydown', function(e) {
  if (e.keyCode === 39) {
    offset += 90;
    if (offset === 360) {
      offset = 0;
    }
    rotate(imgEl, offset);
  } else if (e.keyCode === 37) {
    offset -= 90;
    if (offset === -360) {
      offset = 0;
    }
    rotate(imgEl, offset);
  }
});

function rotate(el, degrees) {
  // Code for Safari
  el.style.WebkitTransform = `rotate(${degrees}deg)`;
  // Code for IE9
  el.style.msTransform = `rotate(${degrees}deg)`;
  // Standard syntax
  el.style.transform = `rotate(${degrees}deg)`;
}
<img id="imgEl" src="https://static-s.aa-cdn.net/img/ios/1037581527/890273ca9f97b338cd84ab01f7549bc2?v=1">