【问题标题】:Why is my animation not detecting page width?为什么我的动画没有检测到页面宽度?
【发布时间】:2022-01-19 03:19:58
【问题描述】:

我正在尝试让这个 pacman 动画在一组图像中循环,并在它碰到页面边缘时反转方向。

我尝试在 Chrome 中调试,它给了我以下错误

“无法读取null的属性(读取宽度)”

var pos = 0;
//pageWidth is the width of the webpage. This is later used to calculate when Pac-Man needs to turn around. 
const pageWidth = window.innerWidth;
//This array contains all the PacMan movement images
const pacArray = [
  ['./images/PacMan1.png', './images/PacMan2.png'],
  ['./images/PacMan3.png', './images/PacMan4.png'],
];

// this variable defines what direction should PacMan go into:
// 0 = left to right
// 1 = right to left (reverse)
var direction = 0;

// This variable helps determine which PacMan image should be displayed. It flips between values 0 and 1
var focus = 0;

// This function is called on mouse click. Every time it is called, it updates the PacMan image, position and direction on the screen.
function Run() {
  let img = document.getElementById('PacMan');
  let imgWidth = img.width;
  let pageWidth = window.innerWidth;
  focus = (focus + 1) % 2;
  direction = checkPageBounds(direction, imgWidth, pos, pageWidth);
  img.src = pacArray[direction][focus];
  if (direction) {
    pos -= 20;
    img.style.left = pos + 'px';
  } else {
    pos += 20;
    img.style.left = pos + 'px';
  }
}

setInterval(Run,200)




// This function determines the direction of PacMan based on screen edge detection. 
function checkPageBounds(direction, imgWidth, pos, pageWidth) {
 

  if (direction == 1 & pos + imgWidth > pageWidth) direction== 0;
  if (direction == 0 & pos < 0) direction == 1;
  
  
  //
  return direction;
}


module.exports = checkPageBounds;

【问题讨论】:

    标签: javascript animation pacman


    【解决方案1】:

    您的示例未显示模板/html。元素id(PacMan)写对了吗?

    这个例子应该在控制台打印一个 200:

    <img id="PacMan" src="https://picsum.photos/200/300" />
    
    const img = document.getElementById('PacMan');
    let imgWidth = img.width;
    

    只是一点题外话:看看“var”、“const”和“let”之间的区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多