2014-11-03 136 views
1

我在這裏試圖用此代碼在直線上畫一個移動的圓圈。但即時通訊語言錯了。幫我糾正這段代碼。從畫布左側向右側直線移動圓圈

<script> 

var canvas = document.getElementById("myCanvas"); 
var context = canvas.getContext("2d"); 

function draw_circle (circleX, circleY, radius, fill) { 
    context.fillStyle = "black"; 
    context.fillRect(0, 0, 800, 300); 

    context.strokeStyle = "red"; 
    context.strokeRect(5, 5, 790, 290); 

    var speed = 5 

    context.fillStyle = fill; 
    context.arc(circleX, circleY, radius, 0, Math.PI*2); 
    context.fill(); 
} 

setInterval(draw_circle(100,100, 30 , "cyan"), 33); 

</script> 

回答

1

你必須清楚你的畫布(使用canvas.width = canvas.widthclearRect()

需要注意的是,你將不得不爲了增加context.beginPath()clearRect()做他的工作。

一旦完成,你只需增加你的弧的x位置。

var canvas = document.getElementById("myCanvas"); 
 
var context = canvas.getContext("2d"); 
 

 
function draw_circle (circleX, circleY, radius, fill) { 
 
    //clear the canvas 
 
    context.clearRect(0,0,canvas.width, canvas.height); 
 

 
    context.beginPath(); 
 
    context.fillStyle = "black"; 
 
    context.fillRect(0, 0, 800, 300); 
 

 
    context.strokeStyle = "red"; 
 
    context.strokeRect(5, 5, 790, 290); 
 
    var speed = 5; 
 
    //just a loop if you don't want it simply use `i+=speed;` 
 
    (i>canvas.width+radius)?i=(radius*-2):i+=speed; 
 
    context.fillStyle = fill; 
 
    context.arc(circleX, circleY, radius, 0, Math.PI*2); 
 
    context.fill(); 
 
} 
 

 
var i=0; 
 

 
setInterval(function(){draw_circle(i,100, 30 , "cyan")}, 33);
<canvas id = "myCanvas"></canvas>

+1

並以bouce它左至右做這樣的事情http://jsfiddle.net/c4vxb9tx/(基於回答,您可以用速度取代vectorx如果你想) – dwana 2014-11-03 15:15:54

+0

明白了!謝謝你的答案kaiido。 :)。 – Drew 2014-11-03 15:56:04

+0

和dwana,我有一個問題。可以在代碼中使用參數嗎?我想了解更多如何在我的代碼中添加參數:) – Drew 2014-11-03 15:57:44