【发布时间】:2017-11-07 18:04:53
【问题描述】:
可能的修复(随着时间的推移效率/性能问题?)
let i = 0;
function float() {
yPos += Math.sin(i);
i += .01 * yVel;
}
我正在尝试在 HTML5 Canvas 中重新创建“浮动”效果。 我想要做的是试图让图像上下“浮动”。 绘制图像并运行 float() 函数以计算图像的下一个 y 位置。我已经让它向下或向上浮动,但不是在图像浮动示例 100 像素(向上或向下)后如何更改方向。我该怎么做?
我在这里上传了画布:https://stuff.darkleaks.net/HTML5%20WP/cheshire/
如你所见,图像飘了下来,然后放慢了速度。在它停止移动后,我想改变浮动方向。 float() 函数是我尝试这样做的地方。
// Request animation frame
const requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
// Canvas
const c = document.getElementById('canvas');
const ctx = c.getContext('2d');
// Set full-screen
c.width = window.innerWidth;
c.height = window.innerHeight;
// Framerate settings
// Better not touch theese if you
// do not know what you are doing
let fps = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) ? 29 : 60;
let now, delta;
let then = Date.now();
const interval = 1000 / fps;
// Preparation below this comment line
const background = new Image();
const cheshire = new Image();
const images = [background, cheshire];
var imagesCount = images.length;
background.onload = cheshire.onload;
background.src = 'bg.png';
cheshire.src = 'cheshire.png';
let originalXPos = c.width / 2 - images[1].width / 2;
let originalYPos = c.height / 2 - images[1].height / 2;
let xPos = c.width / 2 - images[1].width / 2;
let yPos = c.height / 2 - images[1].height / 2;
let xVel = 0;
let yVel = .5;
// Draw
function draw() {
// Loop
requestAnimationFrame(draw);
now = Date.now();
delta = now - then;
if (delta > interval) {
// Calculate then
then = now - (delta % interval);
// All your own stuff here
drawImages();
float();
}
}
// Draw background
function drawImages() {
ctx.drawImage(images[0], 0, 0)
ctx.drawImage(images[1], xPos, yPos);
}
function float() {
yPos += 1 / yVel;
yVel += .05;
// IF the image has floated 100 px (up or down)
// change direction
}
// Returns an random integer between
// min and max
function randInt(min, max) {
max = max === undefined ? min - (min = 0) : max;
return Math.floor(Math.random() * (max - min) + min);
}
// Cursor coordinates X & Y
function clicked(e) {
let x, y;
if (e.offsetX) {
x = e.offsetX;
y = e.offsetY;
} else if (e.layerX) {
x = e.layerX;
y = e.layerY;
}
// Do something...
}
$('canvas').on('click', function(e) {
clicked(e);
});
requestAnimationFrame(draw);nter code here
【问题讨论】: