按下右箭头键和左箭头键时如何在HTML5画布上旋转图像

时间:2015-10-01 06:04:21

标签: javascript html5-canvas

我需要帮助尝试旋转我在画布上绘制的矩形。一旦我按下键盘上的箭头键,我希望矩形的顶部向右或向左旋转。到目前为止,这是我的代码:

Canvas

HTML:

  <body >
    <div id="canvas-container">
      <canvas id="canvas" width="500" height="400"></canvas>
    </div>
  </body>

CSS:

canvas {
   display: inline;
}

使用Javascript:

document.addEventListener("DOMContentLoaded", function() {
    drawBorder();
});

var canvas;
var context;
var size;

drawRectangle();
drawHalfCircle();

function drawBorder() {
    canvas = document.getElementById("canvas");
    context = canvas.getContext('2d');
    size = {
        x: canvas.width,
        y: canvas.height
    };
    //have to set colors etc befor it is drawn
    context.strokeStyle = 'black';
    //takes 4 parameters
    context.strokeRect(0, 0, size.x, size.y);
}

function drawRectangle() {
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    ctx.rect(246, 290, 8, 80);
    ctx.stroke();
}

function drawHalfCircle(){
    var c= document.getElementById("canvas");
    var ctx=c.getContext("2d");
    ctx.beginPath();
    ctx.arc(250,579,308,1.2*Math.PI, 1.8*Math.PI);
    ctx.stroke();
}

1 个答案:

答案 0 :(得分:2)

我已经嘲笑了一些事情就是你想要的正确线条。

document.addEventListener("DOMContentLoaded", function() {
    drawBorder();
});

var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var size;
var angle = 0;

setInterval(function () {
    context.save(); 
    context.clearRect(0, 0, canvas.width, canvas.height); 

    drawBorder();
    drawHalfCircle();
    drawRectangle();

    context.restore(); 
 }, 100);

function drawBorder() {
    size = {
        x: canvas.width,
        y: canvas.height
    };

    //have to set colors etc befor it is drawn
    context.strokeStyle = 'black';
    //takes 4 parameters
    context.strokeRect(0, 0, size.x, size.y);
}

function drawRectangle() {
    context.rotate(Math.PI / 180 * (angle));
    context.rect(246, 290, 8, 80);
    context.stroke();
}

function drawHalfCircle(){
    context.beginPath();
    context.arc(250,579,308,1.2*Math.PI, 1.8*Math.PI);
    context.stroke();
}

document.onkeydown = function(e) {
    var event = window.event ? window.event : e;

    if (e.keyCode == '37') {
       angle += 5;
    }
    else if (e.keyCode == '39') {
       angle -= 5;
    }
}

基本上设置间隔并重绘(即电影中的帧)并通过变量旋转。

在此处查看演示 https://jsbin.com/qititacazu/edit?js,output

如果你想翻译它以便它会围绕另一个点旋转做类似的事情。

context.translate(246, 290); 
context.rotate(Math.PI / 180 * (angle));
context.rect(-4, 0, 4, 80);