在圆形方向上移动图像的

moving of an image in circular direction

本文关键字:移动 图像 方向      更新时间:2023-09-26

我想在圆形方向移动图像。我用了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);
}

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

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>