Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  97] [ 6]  / answers: 1 / hits: 40617  / 12 Years ago, tue, march 20, 2012, 12:00:00

I need help with making an image float onto the canvas in HTML5 and JavaScript. I have been googling around and have not found anything. I can draw shapes on the screen but I dont know how to animate them.
I want couple of different images to float in on the canvas from different directions.
Can someone please help me with this? after 4 hours of googling all I could do was this



<script type = Text/JavaScript>
function Animate(){
var canvas=document.getElementById(myCanvas);
var ctx=canvas.getContext(2d);

var img = new Image();

img.onload = function ()
{
ctx.drawImage(img,20,20,300,300);

};
img.src = vb.png;
}
</script>
</head>
<body>
<canvas id=myCanvas height=200 width=800></canvas>
<br><button onclick=Animate();>Restart</button>


There seem to be plenty of tutorials on animating shapes but I want to load up my own pictures and have them fly in onto the canvas.


More From » image

 Answers
1

Try this very basic demo of a canvas animation:



http://jsfiddle.net/bDQ6b/2/



window.addEventListener('load', function () {
var
img = new Image,
ctx = document.getElementById('myCanvas').getContext('2d');

img.src = 'http://www.gravatar.com/avatar/a1f80339c0cef95be6dc73e0ac510d5d?s=32&d=identicon&r=PG';
img.addEventListener('load', function () {

var interval = setInterval(function() {
var x = 0, y = 0;

return function () {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, x, y);

x += 1;
if (x > ctx.canvas.width) {
x = 0;
}
};
}(), 1000/40);
}, false);
}, false);





There is a lot which could be done better though. E.g.:




  • using requestAnimationFrame instead of an interval


  • preloading the images in a more convenient way


  • using velocities and time differences (from last to current frame) instead of fixed increments


  • and many more




but, as all this would make the example way too complicated, I'll leave it as it is and hope you'll read up on those topics while learning.


[#86719] Monday, March 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
warren

Total Points: 679
Total Questions: 115
Total Answers: 78

Location: Antigua and Barbuda
Member since Sat, Apr 24, 2021
3 Years ago
;