1
可能修復(efficency /性能比較的問題隨着時間的推移?)HTML帆布浮空效果
let i = 0;
function float() {
yPos += Math.sin(i);
i += .01 * yVel;
}
我試圖重新創建HTML5畫布「浮動」的效果。 我想要做的是試圖讓圖像上下浮動。 繪製圖像並運行float()函數來計算圖像的下一個y位置。我已經獲得它浮動下來,或上升,但沒有如何改變圖像浮動後例如100px(上或下)的方向。我將如何做到這一點?
我已上載這裏的畫布: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
Foun d一個更好的解決方案。我真的不知道它是否有效,因爲隨着時間的推移,我會變得非常大。 但我現在得到的解決方案是這樣的: let i = 0;函數float(){yPos + = Math.sin(i); i + = .01 * yVel; } – Kaizokupuffball