Move objects - Javascript Canvas

Javascript examples for Canvas:Object

Description

Move objects

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

body{ background-color: ivory; }
#container{//from  w w  w.  j av a  2 s  . c  om
   position:relative;
   border:1px solid green;
   width:1380px;
   height:1315px;
}
#frame{
   position:absolute;
   top:0px;
   left:0px;
   border:1px solid red;
}
#picture{
   position:absolute;
   top:66px;
   left:67px;
   border:1px solid blue;
}

      </style> 
      <script>
    $(function(){
        var frame=document.getElementById("frame");
        var ctxFrame=frame.getContext("2d");
        var picture=document.getElementById("picture");
        var ctxPicture=picture.getContext("2d");
        var img=new Image();
        img.onload=function(){
            ctxFrame.drawImage(this,0,0,frame.width,frame.height);
        }
        img.src="https://www.java2s.com/style/demo/Google-Chrome.png";
        var dx= 4;
        var dy=4;
        var y=150;
        var x=10;
        function draw(){
            ctxPicture.clearRect(0,0,243,182);
            ctxPicture.beginPath();
            ctxPicture.fillStyle="#0000ff";
            ctxPicture.arc(x,y,20,0,Math.PI*2,true);
            ctxPicture.closePath();
            ctxPicture.fill();
            if( x<10 || x>225)  dx=-dx;
            if( y<10 || y>160)  dy=-dy;
            x+=dx;
            y+=dy;
          }
        setInterval(draw,60);
    }); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <div id="container"> 
         <canvas id="frame" width="380" height="315"></canvas> 
         <canvas id="picture" width="243" height="182"></canvas> 
      </div>  
   </body>
</html>

Related Tutorials