2016-10-08 83 views
0

我想以圓形方向移動圖像。 我用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); 
} 
+0

是'angle'定義的地方嗎? – Tyr

+0

您正在設置圖像元素的樣式,並期望畫布改變。你也是在加載時異步繪製這兩個圖像,這是可行的,但我有點懷疑你完全明白它的作用。 – ASDFGerte

+0

是.........角度是0或.5等等...... – jasminavas

回答

0

看到這個版本旋轉的恆星的帆布作爲參考的(如要求現改爲圖像,誰知我的強大的繪畫技巧!)。請再次注意,您的更新應使用畫布上的繪製調用,而不是在畫布上不關心的圖像元素上設置樣式。理想情況下,您應該在啓動任何內容之前加載圖像。

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>

+0

感謝您的寶貴回覆........ – jasminavas

+0

但我的問題是......我曾經使用過一個圖像球......它必須......我的程序與物理學中的振盪有關.....所以我需要沿着圓圈旋轉球,用戶選擇的角度 – jasminavas

+0

有沒有機會旋轉畫布上的圖像? – jasminavas