在圆形方向上移动图像

时间:2016-10-08 15:13:46

标签: javascript

我希望以圆周方向移动图像。 我使用了setTimeout函数......但它没有用。

我的代码是:

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);
}

1 个答案:

答案 0 :(得分:0)

在画布上看到这个版本的旋转星(现在请求改为图像,看看我强大的绘画技巧!)作为参考。再次注意,您的更新应该使用画布上的绘制调用ctx.drawImage(ball_image, x, y, ball_image_size, ball_image_size);,而不是在图像元素上设置样式,画布不关心它。最理想的情况是,您应该在开始之前加载图像。

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>

相关问题