@@ -314,4 +314,50 @@ function keyRight() {// pressed right arrow key
314
314
document . getElementById ( "right_arrow" ) . style . transform = "scale(0.9)" ;
315
315
}
316
316
}
317
+ //增加一个触摸屏幕事件,让Paddle水平移动距离和触摸点水平移动距离一致
318
+ var touchXstart = null ;
319
+ function actionStart ( e ) {
320
+ e . preventDefault ( ) ;
321
+ //判断是鼠标左键点击还是触摸
322
+
323
+ if ( e . touches && touchXstart == null ) { //如果是触摸 touchXstart等于第一个touch点的x坐标
324
+ touchXstart = e . touches [ 0 ] . pageX ;
325
+ } else { //如果是鼠标 touchXstart等于鼠标的x坐标
326
+ touchXstart = e . pageX ;
327
+ }
328
+
329
+
330
+ }
331
+ function actionEnd ( e ) {
332
+ e . preventDefault ( ) ;
333
+ touchXstart = null ;
334
+ }
335
+ function actionMove ( e ) {
336
+ //e.preventDefault();
337
+ var dist ;
338
+ //判断是鼠标左键点击还是触摸
339
+ if ( touchXstart != null ) {
340
+ if ( e . touches ) { //如果是触摸 dist等于第一个touch点的x坐标x相对touchXstart的移动距离
341
+ dist = e . touches [ 0 ] . pageX - touchXstart ;
342
+ } else { //如果是鼠标 dist等于鼠标的x坐标x相对touchXstart的移动距离
343
+ dist = e . pageX - touchXstart ;
344
+ }
345
+ // dist 按照画布的放大比例缩放
346
+ var canvasS = document . getElementById ( "canvas" ) ;
347
+ dist = dist / canvas . width * canvasS . clientWidth / 2 ;
348
+
349
+ paddle . x = paddle . x + dist ;
350
+ if ( paddle . x + paddle . w > canvas . width ) paddle . x = canvas . width - paddle . w ;
351
+ if ( paddle . x < 0 ) paddle . x = 0 ;
352
+ }
353
+ }
354
+
355
+
356
+ document . addEventListener ( 'touchstart' , actionStart ) ;
357
+ document . addEventListener ( 'touchend' , actionEnd ) ;
358
+ document . addEventListener ( 'touchmove' , actionMove ) ;
359
+ //相应鼠标点击后移动的事件
360
+ document . addEventListener ( 'mousedown' , actionStart ) ;
361
+ document . addEventListener ( 'mouseup' , actionEnd ) ;
362
+ document . addEventListener ( 'mousemove' , actionMove ) ;
317
363
0 commit comments