使用HTML5移动和旋转

时间:2015-11-12 01:34:04

标签: javascript html5

需要做什么: 粉红色物体应该从左向右移动(单独)。然后,当距离边缘5px时,它应该旋转90度。

有谁知道怎么做?

我很久没有学过javascript了,这是我第一次使用HTML5创建内容。所以它都是全新的。我真的希望你能帮助我更好地理解代码,以及如何让代码移动和旋转。

    <!DOCTYPE html>    
    <html>
    <head>
    <script>
    var canvas, ctx;    
    window.onload = function draw() {
    canvas = document.getElementById("myCanvas");
    ctx = canvas.getContext("2d");
    var height = 90;
    var width = 40;
    var radius = width / 2;
    ctx.clearRect(0,0, canvas.width, canvas.height);
    ctx.fillStyle = "#FFE2E8";
    ctx.strokeStyle = "black";
    ctx.beginPath();
    ctx.moveTo(20,20);
    ctx.lineTo(70,20);
    ctx.arc(70,40,20, -Math.PI/2, Math.PI/2);
    ctx.lineTo(20,60); 
    ctx.lineTo(20,20);
    ctx.closePath;
    ctx.fill();
    ctx.stroke();
    requestAnimationFrame(draw);

   }

   function init() {
   canvas = document.getElementById("myCanvas");
   ctx = canvas.getContext("2d");
   draw();
   }


   </script>
   </head>

   <body>
   <canvas id="myCanvas" width="400" height="300"     style="background:#00CC66">
   </canvas>
   </body>
   </html>

1 个答案:

答案 0 :(得分:0)

var canvas, ctx;
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var radius = 20;
var width = 70;
var margin = 5;
var offsetx = -20
var translate = {
  x: 0,
  y: 0,
  xmax: canvas.width - margin - width + offsetx,
  ymax: canvas.height - margin - width
};
var rotate = 0;
var to_radians = Math.PI / 180;

function draw() {
  ctx.save();
  ctx.translate(translate.x, translate.y);
  if (translate.x >= translate.xmax) {
    translate.x = translate.xmax;
    if (rotate >= 90) {
      rotate = 90;
    } else {
      rotate++;
    }
    
    ctx.rotate(rotate * to_radians);

  } else {
    translate.x++;
  }
  var height = 90;
  var width = 40;
  var radius = width / 2;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#FFE2E8";
  ctx.strokeStyle = "black";
  ctx.beginPath();
  ctx.moveTo(20, 20);
  ctx.lineTo(70, 20);
  ctx.arc(70, 40, 20, -Math.PI / 2, Math.PI / 2);
  ctx.lineTo(20, 60);
  ctx.lineTo(20, 20);
  ctx.closePath;
  ctx.fill();
  ctx.stroke();
  ctx.restore();
  requestAnimationFrame(draw);

}

function init() {
  canvas = document.getElementById("myCanvas");
  ctx = canvas.getContext("2d");
  draw();
}

init();
<canvas id="myCanvas" width="400" height="300" style="background:#00CC66">
</canvas>