vendredi 26 janvier 2018

Course Javascript




<button onclick="myFunctionCourse()">Course</button><br/><br/>
<canvas width="400" height="215" id="canvas" style="border:1px solid #C0C0C0;">
</canvas>

<script>
function myFunctionCourse() {
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var a=Math.floor(100*Math.random());
var b=Math.floor(100*Math.random());
var c=Math.floor(100*Math.random());


var rects=[]
rects.push({x:10,y:050,moveByX:1,interval:a,nextMoveTime:0});
rects.push({x:10,y:100,moveByX:1,interval:b,nextMoveTime:0});
rects.push({x:10,y:160,moveByX:1,interval:c,nextMoveTime:0});

var isFirstLoop=true;

// start the timing loop
requestAnimationFrame(Timer);

function Timer(currentTime){

  // request another timing loop
  // Note: requestAnimationFrame fires only once,
  //       so you must request another loop inside
  //       each current loop
  requestAnimationFrame(Timer);

  if(isFirstLoop){
    isFirstLoop=false;
    for(var i=0;i<rects.length;i++){
      rects[i].nextMoveTime=time+rects[i].interval;
    }
  }

  ctx.clearRect(0,0,cw,ch);
  for(var i=0;i<rects.length;i++){
    drawRect(rects[i],currentTime);
  }

}

function drawRect(r,time){
  if(time>r.nextMoveTime){
    r.x+=r.moveByX;
    r.nextMoveTime=parseInt(time+r.interval);
  }
  ctx.strokeRect(r.x,r.y,110,15);
  ctx.fillText('I move every '+r.interval+'ms',r.x+5,r.y+10);
}}

</script>