phantom phantom - 2 months ago 9
jQuery Question

animate images smoothly up the canvas from the bottom

I am trying to add images to my canvas and then slowly have them slide off the screen. I have it set up so the images keep getting added and they make their way up the screen. I am looking to add a new image on a canvas on a click, and then this same image slowly glides off the screen.

Here is my attempt below. it adds images to the canvas, and they move up the screen, but its an eyesore, and not the desired behavior.



var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = windowWidth;
canvas.height = windowHeight;
var x = windowHeight;


function newImage() {
var images = [
'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
'http://www.convoy.me/image/landing/Scratcher.png',
'http://www.convoy.me/image/landing/push_harder_0006.png',
'http://www.convoy.me/image/landing/Scratcher.png',
'http://www.convoy.me/image/landing/Screen-Shot-2015-12-04-at-17.14.41.jpg'

];
var randomImage = parseInt(Math.random() * images.length);
var randomPosition = parseInt(Math.random() * 1200);


var imageObj = new Image();
imageObj.onload = function() {
ctx.drawImage(imageObj, randomPosition, x, 200, 200);
};
imageObj.src = images[randomImage];

}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
x--;
newImage();
}

setInterval(draw, 50);
canvas.addEventListener("click", draw, false);

<canvas id="canvas"></canvas>




Answer

I hope this code will helpful for you.

var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = windowWidth;
canvas.height = windowHeight;


function newImage() {
    var randomPosition = parseInt(Math.random() * 1200);
    var images = [
        'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
        'http://www.convoy.me/image/landing/Scratcher.png',
        'http://www.convoy.me/image/landing/push_harder_0006.png',
        'http://www.convoy.me/image/landing/Scratcher.png',
        'http://www.convoy.me/image/landing/Screen-Shot-2015-12-04-at-17.14.41.jpg'
    ];
    var y = windowHeight;
    var randomImage = parseInt(Math.random() * images.length);

    (function draw() {
        var imageObj = new Image();
        imageObj.onload = function () {
            ctx.clearRect(randomPosition - imageObj.width, y, imageObj.width,imageObj.height);
            
            y-=5;
            ctx.drawImage(imageObj, randomPosition - imageObj.width, y, imageObj.width,imageObj.height );

            if (y > -imageObj.height){
                requestAnimationFrame(draw)
            }
        };
        imageObj.src = images[randomImage];
    })();
}

canvas.addEventListener("click", newImage, false);
<canvas id="canvas"></canvas>

Comments