Jump to content

New to html5 canvas


madcat999
 Share

Recommended Posts

I am trying to move to images which have been loaded to the screen so they meet together and stop.  The code is below - one image disappears and they both move in the same direction.  Any help would be appreciated as I am very very new to this and have googled for a whole day (bought a book) and am still not able to work it out.  Thank you

 

   <canvas id="myCanvas" width="578" height="200">

    <p>This browser does not support the <code>canvas</code> element.</p></canvas>
    <script>
 
 
    window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame;
 
// get canvas and create drawing context
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
 
// create image
var img1 = document.createElement("img");
var img2 = document.createElement("img");
 
var xSpeed = 0.05;  //px per ms
var ySpeed = 0.01;
 
function animate(nowTime, lastTime, xPos, yPos) {
    if ((img1.style.width + xPos) > canvas.width) {
        xPos = 0;
        yPos = 0;
    }
 
    var timeDelta = nowTime - lastTime;
    var xDelta = xSpeed * timeDelta;
    var yDelta = ySpeed * timeDelta;
    
    // clear
    context.clearRect(0, 0, canvas.width, canvas.height);
 
    //draw img
    context.drawImage(img1, xPos, yPos);
 
if (xPos < 133) {
requestAnimationFrame(
function(timestamp){animate(timestamp, nowTime, xPos + xDelta, yPos + yDelta)}
);
}
}
 
 
function animate2(nowTime, lastTime, x2Pos, y2Pos) {
    if ((img2.style.width + x2Pos) > canvas.width) {
        x2Pos = 0;
        y2Pos = 90;
    }
 
 
    var timeDelta = nowTime - lastTime;
    var x2Delta = xSpeed * timeDelta;
    var y2Delta = ySpeed * timeDelta;
    
    // clear
    //context.clearRect(0, 0, canvas.width, canvas.height);
 
    //draw img
    context.drawImage(img2, x2Pos, y2Pos);
 
if (x2Pos < 133) {
requestAnimationFrame(
function(timestamp){animate2(timestamp, nowTime, x2Pos + x2Delta, y2Pos + y2Delta)}
);
}
}
animate(0, 0,  10, 1),
animate2(0, 1,  70, 1);
 
    </script>
Link to comment
Share on other sites

  • 1 month later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...