无法弄清楚如何实现这一目标。我有正确的函数触发但是当涉及为什么逻辑不能运行我的脚本时我迷失了。我有一个console.log来显示变量正在更新但动画宽度不会随之更新。
的Javascript
$( document ).ready(function() {
var imgTag = new Image();
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = canvas.width;
var y = 0;
imgTag.onload = animate;
imgTag.src = "http://foodhall.hellogriptest.com/hh/assets/medallion-bounce.png";
var h = window.innerHeight;
var w = window.innerWidth;
canvas.height = h;
canvas.width = w;
//moving image
var mover = {
x: 0,
y: 0,
width: 100,
height: 100,
color: '#000',
down: true,
right: true
}
function animate() {
clear();
render();
rID = requestAnimationFrame(animate);
}
function clear() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function render() {
//set direction
if (mover.down && mover.y >= h - mover.height)
mover.down = false;
if (!mover.down && mover.y <= 0)
mover.down = true;
if (mover.right && mover.x >= w - mover.width)
mover.right = false;
if (!mover.right && mover.x <= 0)
mover.right = true;
//make move
if (mover.right)
mover.x += 6;
else
mover.x -= 6;
if (mover.down)
mover.y += 6;
else
mover.y -= 6;
//drawRectangle(mover);
drawImage(mover);
}
function drawImage(mover) {
context.drawImage(imgTag, mover.x, mover.y); // draw image at current position
}
window.onresize = function() {
W = window.innerWidth;
H = window.innerHeight;
canvas.width = W;
canvas.height = H;
x = W;
console.log(x);
clear();
render();
drawImage(mover);
}
});//ready
Codepen - https://codepen.io/alcoven/pen/KROPrK
答案 0 :(得分:1)
这是一个简单的解决方法。在脚本的开头,您将小写字母w和小写字母h设置为窗口的宽度和高度,但在调整大小功能时,您设置W = window.innerWidth。然后创建大写W变量并赋予innerWidth。小写w变量仍然作为原始宽度存在,这就是渲染所使用的。