jasminavas jasminavas - 1 month ago 17
Javascript Question

moving of an image in circular direction

I'd like to move an image in circular direction.
I used

setTimeout
function... but it didn't work.

My code is:

x = image_size/2+radius*Math.cos(Math.PI*angle)-ball_image_size/2;
y = image_size/2-radius*Math.sin(Math.PI*angle)-ball_image_size/2;

//-----image main circle--------

base_image = new Image();
base_image.src = 'img/test.jpg';
base_image.onload = function()
{
ctx.drawImage(base_image,0,0,image_size,image_size);
};

//------------image ball---------

ball_image = new Image();
ball_image.src = 'img/ball.jpg';
ball_image.onload = function()
{
ctx.drawImage(ball_image, x, y, ball_image_size, ball_image_size);
}

clr = setTimeout('ball()',20);

}

//--------function of animation------------
function ball () {

ball_image.style.left = Math.cos(Math.PI*angle)*radius;
ball_image.style.top = Math.sin(Math.PI*angle)*radius;

angle = angle + .1;
//setTimeout(ball,20);
}

Answer

See this version of a rotating star (as requested now changed to an image, behold my mighty drawing skills!) on a canvas as reference. Note again that your update should use the draw call on the canvas, ctx.drawImage(ball_image, x, y, ball_image_size, ball_image_size); and not set a style on the image element, which the canvas doesn't care about. Optimally, you should load your images before starting anything.

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let radius = canvas.width / 3;
let centerX = canvas.width / 2;
let centerY = canvas.height;
let x, y;
let angle = 0;

let star = new Image();
star.onload = draw;
//Imgur doesn't produce CORS issues luckily
star.src = "http://i.imgur.com/VIofbab.png";

function draw() {
  //minus because it should start on the left
  x = centerX - Math.cos(angle) * radius;
  //minus because canvas y-coord system is from
  //top to bottom
  y = centerY - Math.sin(angle) * radius;

  //Angle is in rad
  angle += Math.PI / 180;
  angle %= Math.PI;
  
  //Draw a star (was circle before)
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(star, x - star.width / 2, y - star.height / 2);
  setTimeout(draw, 50);
};
<html>
  <body>
    <canvas id="canvas" width="320" height="180" style="border:1px solid #000000;">not supported</canvas>
  </body>
</html>