how to move object in circle forward and backward in html5 canvas?

╄→尐↘猪︶ㄣ 提交于 2019-12-05 18:57:08

Using a keymap object makes it easier...

if ( !window.requestAnimationFrame ) {
  window.requestAnimationFrame = ( function() {

    return window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {

      window.setTimeout( callback, 1000 / 60 );

    };

  } )();
}

var canvas = document.getElementById('scene');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var angle = 0;
var cx = 200;
var cy = 200;
var radius = 100;
var speed = 0.1;

var keymap = {
  left: false,
  right: false
};

function doKeyDown(e) {
  var key = event.which;
  switch (key) {
      
    case 37:
      keymap.left = -1;
      break;

    case 39:
      keymap.right = 1;
      break;

  }
}

function doKeyUp(e) {
  var key = event.which;
  switch (key) {
      
    case 37:
      keymap.left = 0;
      break;

    case 39:
      keymap.right = 0;
      break;

  }
}


function drawCircle(x, y, r, c, s) {
  ctx.fillStyle = c;  
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI * 2, false);
  ctx.closePath();
  if(s) ctx.stroke();
  else ctx.fill();
}


function redCircle() {
// increase the angle of rotation
  
  var direction = keymap.left + keymap.right;
  angle +=  speed * direction;

  var x = cx + (radius * Math.cos(angle));
  var y = cy + (radius * Math.sin(angle));
  
  drawCircle(x, y, 10, 'red');

}

var redraw = function() {
  ctx.clearRect(0, 0, w, h);
  drawCircle(cx, cy, radius, 'black', 'stroke');
  redCircle();
  window.requestAnimationFrame(redraw);
};


window.addEventListener("keydown", doKeyDown, true);
window.addEventListener("keyup", doKeyUp, true);

redraw();
html {
    height: 100%;
}
body{
    padding: 0; margin: 0;
    height: 100%;
    width: 100%;
    overflow: hidden;
}
/* Some basic styling */
#scene {
	display: block;
	border: 1px solid blue;
	margin: 50px auto;
}
<canvas id="scene" width=400 height=400></canvas>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!