8

Html飞机大战(十七): 优化移动端 - 养肥胖虎

 1 year ago
source link: https://www.cnblogs.com/FatTiger4399/p/16708996.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Html飞机大战(十七): 优化移动端

好家伙,继续优化,

好家伙,我把我的飞机大战发给我的小伙伴们玩

期待着略微的赞赏之词,然后他们用手机打开我的给他们的网址

然后点一下飞机就炸了。

游戏体验零分

(鼠标点击在移动端依旧可以生效)

好了所以我们来优化一下这个触屏移动事件

由于没有参考,就去翻文档了

触摸事件分三个:touchstart、touchmove和touchend

看名字大概是触摸点开始,触摸点移动,触摸点离开。

于是开始试探性的增加一个屏幕触碰事件

//为canvas绑定一个屏幕触碰事件 触碰点正好在飞机图片的正中心
    canvas.addEventListener("touchstart",(e)=>{
      let x = e.offsetX;
      let y = e.offsetY;
      hero.x = x - hero.width / 2;
      hero.y = y - hero.height / 2;
    })

然后就寄了,参数有问题。

移动触点事件touchstart事件是不能直接拿到鼠标在canvas画布中的坐标。

参数e.offsetX直接就报undefind

去查百度了:

javaScript — touch事件详解(touchstart、touchmove和touchend) - 腾讯云开发者社区-腾讯云 (tencent.com)

(挺详细的)

每个Touch对象包含的属性如下。

 clientX:触摸目标在视口中的x坐标。
 clientY:触摸目标在视口中的y坐标。
 identifier:标识触摸的唯一ID。
 pageX:触摸目标在页面中的x坐标。
 pageY:触摸目标在页面中的y坐标。
 screenX:触摸目标在屏幕中的x坐标。
 screenY:触摸目标在屏幕中的y坐标。
 target:触目的DOM节点目标。

还是拿不到鼠标在canvas的坐标

那我们试着拿到页面中的坐标然后再去进行加减操作,然后还是不行

好家伙,拿不到鼠标移动时鼠标在canvas画布中的坐标,

所以,我们动点歪脑经

2501855-20220921230452531-302431801.png

我们拿到屏幕坐标来计算就好了

canvas.addEventListener("touchmove", (e) => {
      // let x = e.pageX;
      // let y = e.pageY;
      console.log(e);
      // let x = e.touches[0].clientX;
      // let y = e.touches[0].clinetY;
      let x = e.touches[0].pageX;
      let y = e.touches[0].pageY;
      // let x = e.touches[0].screenX;
      // let y = e.touches[0].screenY;
      let write1 = (document.body.clientWidth - 480) / 2;
      let write2 = (document.body.clientHeight - 650) / 2;
      hero.x = x - write1 - hero.width / 2;
      hero.y = y - write2 - hero.height / 2;

      // hero.x = x - hero.width / 2;
      // hero.y = y - hero.height / 2;
      console.log(x, y);
      console.log(document.body.clientWidth, document.body.clientHeight);
      e.preventDefault(); // 阻止屏幕滚动的默认行为

    })

猜猜我干了什么

2501855-20220921233217307-1436588635.png

 我们想办法用页面坐标减去空白部分长度就可以得到鼠标在canvas画布中的坐标了

纵坐标同理

(nice)

 

2501855-20220921233512069-1122320174.gif

 (此处为平板模式,完成了触屏连续移动)

效果还行


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK