我正在尝试将图像添加到 Canvas 上,然后慢慢地让它们从屏幕上滑落。我已经设置好了,这样图像就会不断添加,并且它们会出现在屏幕上。我希望通过单击在 Canvas 上添加新图像,然后该图像慢慢地从屏幕上滑落。
这是我的尝试如下。它将图像添加到 Canvas 上,并将图像向上移动到屏幕上,但这很碍眼,而不是所需的行为。
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>
最佳答案
希望这段代码对您有所帮助。
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>
关于javascript - 将图像从底部平滑地移动到 Canvas 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39792292/