5 / 7 / 2
Регистрация: 06.04.2015
Сообщений: 62
1

Ошибка Uncaught TypeError: Cannot read property 'offsetX' of undefined

03.04.2016, 00:47. Показов 5062. Ответов 6
Метки нет (Все метки)

Не могу избавиться от ошибки
Uncaught TypeError: Cannot read property 'offsetX' of undefined

в этом коде

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getClickXY(event)
  {
    restart.addEventListener('click', getClickXY, false);
    var x;
    var y;
     if(event.offsetX){
        x = event.offsetX;
        y = event.offsetY;
    }
    else if(event.layerX){
       x = event.layerX;
       y = event.layerY;
    }
    location.reload();
  }
помогите разобраться
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
03.04.2016, 00:47
Ответы с готовыми решениями:

Ошибка Uncaught TypeError: Cannot read property 'toggle' of undefined
В js файле есть код: $( document ).ready(function() { var value = $("#s_theme").text(); var...

Uncaught TypeError: Cannot read property 'value' of undefined
Не могу понять в чем проблема выдает ошибку Uncaught TypeError: Cannot read property 'value' of...

Uncaught TypeError: Cannot read property 'createRange' of undefined
Вроде б все просто, но не работает function AddTags(Tag,Tag2) { document.forma.content.focus();...

Uncaught TypeError: Cannot read property 'order' of undefined
orderBy: function(event, container, element){ var id = 'id-' + this.getID(container); ...

6
Ренегат
Эксперт HTML/CSS
1740 / 1085 / 386
Регистрация: 06.08.2014
Сообщений: 5,203
Записей в блоге: 1
03.04.2016, 00:56 2
Javascript
1
    var x, y, event = event || window.event;
Добавлено через 13 секунд
это для ие по идее
0
5 / 7 / 2
Регистрация: 06.04.2015
Сообщений: 62
03.04.2016, 01:36  [ТС] 3
немного не понял
это поможет убрать ошибку?
у меня в хроме она
0
Hello Kitty
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
03.04.2016, 02:18 4
Цитата Сообщение от DenisDavydov Посмотреть сообщение
немного не понял
это поможет убрать ошибку?
у меня в хроме она
ваш код рабочий в хроме.
вы уверены что правильно повесили getClickXY?
Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function getClickXY(event)  {
  //  restart.addEventListener('click', getClickXY, false);
    var x;
    var y;
     if(event.offsetX){
        x = event.offsetX;
        y = event.offsetY;
    }
    else if(event.layerX){
       x = event.layerX;
       y = event.layerY;
    }
    //location.reload();
    
    console.info(x,y);
  }
  
  document.getElementById('divId').onclick = getClickXY;
HTML5
1
2
3
<div id="divId" style="width: 500px; height: 500px; background: #F01;">
 
</div>
https://jsfiddle.net/3eoftx8t/1/
0
5 / 7 / 2
Регистрация: 06.04.2015
Сообщений: 62
03.04.2016, 23:26  [ТС] 5
не уверен
все работает как надо, но когда объекты сталкиваются ошибка эта вылезает
она в принципе никак не мешает, но не приятно
возможно по полному коду понятно будет в чем ошибка?

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
window.onload = init;
 
var map;
var ctxMap;
 
var pl;
var ctxPl;
 
var enemyCv;
var ctxEnemy;
 
var stats;
var ctxStats;
 
var restart = document.getElementById('restart');
var ctxRestart;
 
 
var drawBtn;
var clearBtn;
 
var gameWidth = 800;
var gameHeight = 500;
 
var background = new Image();
background.src = "fon.jpg";
 
var background1 = new Image();
background1.src = "fon.jpg";
 
var tiles = new Image();
tiles.src = "player.png";
 
var player;
var enemies = [];
 
var isPlaying;
 
var health = 0;
var timerId = setInterval(resetHealth, 100) ;
 
var mapX = 0;
var map1X = gameWidth;
 
 
 
var requestAnimFrame = window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.oRequestAnimationFrame ||
                        window.msRequestAnimationFrame;
                        
function init()
{
    map = document.getElementById("map");
    ctxMap = map.getContext("2d");
    
    pl = document.getElementById("player");
    ctxPl = pl.getContext("2d");
    
    enemyCvs = document.getElementById("enemy");
    ctxEnemy = enemyCvs.getContext("2d");
    
    stats = document.getElementById("stats");
    ctxStats = stats.getContext("2d");
    
    restart = document.getElementById("restart");
    ctxRestart = restart.getContext("2d");
    
    map.width = gameWidth;
    map.height = gameHeight;
    pl.width = gameWidth;
    pl.height = gameHeight;
    enemyCvs.width = gameWidth;
    enemyCvs.height = gameHeight;
    stats.width = gameWidth;
    stats.height = gameHeight;
    restart.width = gameWidth;
    restart.height = gameHeight;
    
    ctxStats.fillStyle = "#000";
    ctxStats.font = "bold 15pt Arial";
    
    ctxRestart.fillStyle = "#000";
    ctxRestart.font = "bold 15pt Arial";
    
    drawBtn = document.getElementById("drawBtn");
    clearBtn = document.getElementById("clearBtn");
    
    drawBtn.addEventListener("click", drawRect, false);
    clearBtn.addEventListener("click", clearRect, false);
    
    player = new Player();
    
    resetHealth;
    
    startLoop();
    
    document.addEventListener("keydown", checkKeyDown, false);
    document.addEventListener("keyup", checkKeyUp, false);
}
 
 
function resetHealth()
{
      var invervat = 1 ;
    var end = 10 ;
    
    if(health < end) {
        health += invervat ;
    } else {
        health += 1 ;
    }
}
 
 
function spawnEnemy(count)
{
    for(var i = 0; i < count; i++)
    {
        enemies[i] = new Enemy();
    }
}
 
function startCreatingEnemies()
{   
    spawnEnemy(10);
}
 
 
function loop()
{
    if(isPlaying)
    {
        draw();
        update();
        requestAnimFrame(loop);
    }
}
 
function startLoop()
{
    isPlaying = true;
    loop();
    startCreatingEnemies();
}
 
function stopLoop()
{
    isPlaying = false;
}
 
function draw()
{
    player.draw();
    clearCtxEnemy();
    for(var i = 0; i < enemies.length; i++)
    {
        enemies[i].draw();
    }
}
 
function update()
{
    moveBg();
    drawBg();
    updateStats();
    player.update();
    
    for(var i = 0; i < enemies.length; i++)
    {
        enemies[i].update();
    }
}
 
function moveBg()
{
    var vel = 4;
    mapX -= 4;
    map1X -= 4;
    if(mapX+gameWidth<0) mapX = gameWidth-5;
    if(map1X+gameWidth<0) map1X = gameWidth-5;
}
 
function Player()
{
    this.srcX = 0;
    this.srcY = 0;
    this.drawX = 10;
    this.drawY = 200;
    this.width = 50;
    this.height = 50;
    this.speed = 3;
    
    //For keys
    this.isUp = false;
    this.isDown = false;
    this.isRight = false;
    this.isLeft = false;
    
    
    this.speed = 10;
}
 
function Enemy()
{
    this.srcX = 0;
    this.srcY = 50;
    this.drawX = Math.floor(Math.random() * gameWidth) + gameWidth;
    this.drawY = Math.floor(Math.random() * gameHeight);
    this.width = 50;
    this.height = 50;
    
    this.speed = 7;
    
}
 
 
Enemy.prototype.draw = function()
{
    ctxEnemy.drawImage(tiles, this.srcX, this.srcY, this.width, this.height,
    this.drawX, this.drawY, this.width, this.height);
}
 
Enemy.prototype.update = function()
{
    this.drawX -= 7;
    if(this.drawX + this.width < 0)
    {
    this.drawX = Math.floor(Math.random() * gameWidth) + gameWidth;
    this.drawY = Math.floor(Math.random() * gameHeight);
    }
}
    
Enemy.prototype.destroy = function()
{
    enemies.splice(enemies.indexOf(this), 1);
}   
    
Player.prototype.draw = function()
{
    clearCtxPlayer();
    ctxPl.drawImage(tiles, this.srcX, this.srcY, this.width, this.height,
    this.drawX, this.drawY, this.width, this.height);
}
 
 
 
Player.prototype.update = function()
{
    
    if(this.drawX < 0) this.drawX = 0;
    if(this.drawX > gameWidth - this.width) this.drawX = gameWidth - this.width;
    if(this.drawY < 0) this.drawY = 0;
    if(this.drawY > gameHeight - this.height) this.drawY = gameHeight - this.height;
 
    for(var i = 0; i < enemies.length; i++)
    {
        if(this.drawX <= enemies[i].drawX + enemies[i].width &&
            this.drawX + this.width >= enemies[i].drawX  &&
            this.drawY + this.height >= enemies[i].drawY &&
            this.drawY <= enemies[i].drawY + enemies[i].height)
        {
            updateRestart();
        }
    }
    
    this.chooseDir();
}
 
 
Player.prototype.chooseDir = function()
{
    if(this.isUp)
        this.drawY -= this.speed;
    if(this.isDown)
        this.drawY += this.speed;
    if(this.isRight)
        this.drawX += this.speed;
    if(this.isLeft)
        this.drawX -= this.speed;
}
 
function checkKeyDown(e)
{
    var keyID = e.keyCode || e.which;
    var keyChar = String.fromCharCode(keyID);
    
    if(keyChar == "W")
    {
        player.isUp = true;
        e.preventDefault();
    }
    if(keyChar == "S")
    {
        player.isDown = true;
        e.preventDefault();
    }
    if(keyChar == "D")
    {
        player.isRight = true;
        e.preventDefault();
    }
    if(keyChar == "A")
    {
        player.isLeft = true;
        e.preventDefault();
    }
}
 
function checkKeyUp(e)
{
    var keyID = e.keyCode || e.which;
    var keyChar = String.fromCharCode(keyID);
    
    if(keyChar == "W")
    {
        player.isUp = false;
        e.preventDefault();
    }
    if(keyChar == "S")
    {
        player.isDown = false;
        e.preventDefault();
    }
    if(keyChar == "D")
    {
        player.isRight = false;
        e.preventDefault();
    }
    if(keyChar == "A")
    {
        player.isLeft = false;
        e.preventDefault();
    }
}
 
function drawRect()
{
    ctxMap.fillStyle = "green";
    ctxMap.fillRect(10, 10, 100, 100);
}
 
function clearRect()
{
    ctxMap.clearRect(0, 0, 800, 500);
}
 
function clearCtxPlayer()
{
    ctxPl.clearRect(0, 0, gameWidth, gameHeight);
}
 
function clearCtxEnemy()
{
    ctxEnemy.clearRect(0, 0, gameWidth, gameHeight);
}
 
function updateStats()
{
    ctxStats.clearRect(0, 0, gameWidth, gameHeight);
    ctxStats.fillText("Score: " + health, 10, 20);
}
 
function updateRestart()
{   
    ctxRestart.clearRect(0, 0, gameWidth, gameHeight);
    ctxRestart.fillText("RESTART ", 350, 250);
    getClickXY(event);
}
 
function getClickXY(event)
  {
      
    restart.addEventListener('click', getClickXY, false);
    var clickX = (event.layerX == undefined ? event.offsetX : event.layerX) + 1;
    var clickY = (event.layerY == undefined ? event.offsetY : event.layerY) + 1;
   location.reload();
  }
  
function drawBg()
{
    ctxMap.clearRect(0, 0, gameWidth, gameHeight);
    ctxMap.drawImage(background, 0, 0, 800, 480,
    mapX, 0, gameWidth, gameHeight);
    ctxMap.drawImage(background1, 0, 0, 800, 480,
    map1X, 0, gameWidth, gameHeight);
}
Добавлено через 1 час 14 минут
Вопрос еще
Можно ли скрипт запустить заново каким нибудь другим способом кроме location.reload(); ?
0
Hello Kitty
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
04.04.2016, 05:32 6
Лучший ответ Сообщение было отмечено DenisDavydov как решение

Решение

я бы сделал так.
Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
<canvas id="map"></canvas>
<canvas id="player"></canvas>
<canvas id="enemy"></canvas>
<canvas id="stats"></canvas>
<canvas id="restart"></canvas>
<button id="drawBtn">drawBtn</button>
<button id="clearBtn">clearBtn</button>
 
<script>
 
(function() {
 
 
 
var map;
var ctxMap;
 
var pl;
var ctxPl;
 
var enemyCv;
var ctxEnemy;
 
var stats;
var ctxStats;
 
var restart = document.getElementById('restart');
var ctxRestart;
 
 
var drawBtn;
var clearBtn;
 
var gameWidth = 800;
var gameHeight = 500;
 
var background = new Image();
background.src = "http://anticache.img0.joyreactor.cc/pics/post/%D0%9A%D0%BB%D0%B8%D0%BA%D0%B0%D0%B1%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE-art-%D0%BA%D1%80%D0%B0%D1%81%D0%B8%D0%B2%D1%8B%D0%B5-%D0%BA%D0%B0%D1%80%D1%82%D0%B8%D0%BD%D0%BA%D0%B8-%D0%B1%D0%BE%D0%BB%D1%8C%D1%88%D0%B8%D0%B5-%D0%BA%D0%B0%D1%80%D1%82%D0%B8%D0%BD%D0%BA%D0%B8-862058.jpeg";//fon.jpg";
 
var background1 = new Image();
background1.src = "http://anticache.img1.joyreactor.cc/pics/post/%D0%9A%D0%BB%D0%B8%D0%BA%D0%B0%D0%B1%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE-%D0%BA%D1%80%D0%B0%D1%81%D0%B8%D0%B2%D1%8B%D0%B5-%D0%BA%D0%B0%D1%80%D1%82%D0%B8%D0%BD%D0%BA%D0%B8-%D0%B1%D0%BE%D0%BB%D1%8C%D1%88%D0%B8%D0%B5-%D0%BA%D0%B0%D1%80%D1%82%D0%B8%D0%BD%D0%BA%D0%B8-%D0%BA%D0%BE%D1%81%D0%BC%D0%BE%D1%81-860583.jpeg";//fon.jpg";
 
var tiles = new Image();
tiles.src = "http://anticache.img1.joyreactor.cc/pics/post/%D0%9E%D1%80%D0%B1%D0%B8%D1%82%D1%8B-%D0%90%D1%81%D1%82%D0%B5%D1%80%D0%BE%D0%B8%D0%B4%D0%BE%D0%B2-%D0%BA%D0%BE%D1%81%D0%BC%D0%BE%D1%81-NASA-828447.jpeg";//player.png";
 
var player;
var enemies = [];
 
var isPlaying;
 
var health = 0;
var timerId = setInterval(resetHealth, 100) ;
 
var mapX = 0;
var map1X = gameWidth;
 
 
 
var requestAnimFrame = window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.oRequestAnimationFrame ||
                        window.msRequestAnimationFrame;
                        
var shutdown = false;                       
                        
var init_once_inc = 0;
function init_once() {
    if ( init_once_inc != 0 ) {
        return;
    }
    init_once_inc++;
    
    var drawBtn = document.getElementById("drawBtn");
    var clearBtn = document.getElementById("clearBtn");
    
    drawBtn.addEventListener("click", drawRect, false);
    clearBtn.addEventListener("click", clearRect, false);   
    
    document.addEventListener("keydown", checkKeyDown, false);
    document.addEventListener("keyup", checkKeyUp, false);  
    
    var restart = document.getElementById("restart");
    restart.addEventListener('click', getClickXY, false);   
}             
             
function init()
{
    init_once();
    
    map = document.getElementById("map");
    ctxMap = map.getContext("2d");
    
    pl = document.getElementById("player");
    ctxPl = pl.getContext("2d");
    
    enemyCvs = document.getElementById("enemy");
    ctxEnemy = enemyCvs.getContext("2d");
    
    stats = document.getElementById("stats");
    ctxStats = stats.getContext("2d");
    
    restart = document.getElementById("restart");
    ctxRestart = restart.getContext("2d");
    
    map.width = gameWidth;
    map.height = gameHeight;
    pl.width = gameWidth;
    pl.height = gameHeight;
    enemyCvs.width = gameWidth;
    enemyCvs.height = gameHeight;
    stats.width = gameWidth;
    stats.height = gameHeight;
    restart.width = gameWidth;
    restart.height = gameHeight;
    
    ctxStats.fillStyle = "#000";
    ctxStats.font = "bold 15pt Arial";
    
    ctxRestart.fillStyle = "#000";
    ctxRestart.font = "bold 15pt Arial";
 
    player = new Player();
    
    health = 0;
    resetHealth();
    
    startLoop();
}
 
 
function resetHealth()
{
    var invervat = 1 ;
    var end = 10 ;
    
    if(health < end) {
        health += invervat ;
    } else {
        health += 1 ;
    }
}
 
 
function spawnEnemy(count)
{
    for(var i = 0; i < count; i++)
    {
        enemies[i] = new Enemy();
    }
}
 
function startCreatingEnemies()
{   
    spawnEnemy(10);
}
 
 
function loop()
{
    if(isPlaying)
    {
        draw();
        update();
        requestAnimFrame(loop);
    }
}
 
function startLoop()
{
    isPlaying = true;
    loop();
    startCreatingEnemies();
}
 
function stopLoop()
{
    isPlaying = false;
}
 
function draw()
{
    player.draw();
    clearCtxEnemy();
    for(var i = 0; i < enemies.length; i++)
    {
        enemies[i].draw();
    }
}
 
function update()
{
    moveBg();
    drawBg();
    updateStats();
    player.update();
    
    for(var i = 0; i < enemies.length; i++)
    {
        enemies[i].update();
    }
}
 
function moveBg()
{
    var vel = 4;
    mapX -= 4;
    map1X -= 4;
    if(mapX+gameWidth<0) mapX = gameWidth-5;
    if(map1X+gameWidth<0) map1X = gameWidth-5;
}
 
function Player()
{
    this.srcX = 0;
    this.srcY = 0;
    this.drawX = 10;
    this.drawY = 200;
    this.width = 50;
    this.height = 50;
    this.speed = 3;
    
    //For keys
    this.isUp = false;
    this.isDown = false;
    this.isRight = false;
    this.isLeft = false;
    
    
    this.speed = 10;
}
 
function Enemy()
{
    this.srcX = 0;
    this.srcY = 50;
    this.drawX = Math.floor(Math.random() * gameWidth) + gameWidth;
    this.drawY = Math.floor(Math.random() * gameHeight);
    this.width = 50;
    this.height = 50;
    
    this.speed = 7;
    
}
 
 
Enemy.prototype.draw = function()
{
    ctxEnemy.drawImage(tiles, this.srcX, this.srcY, this.width, this.height,
    this.drawX, this.drawY, this.width, this.height);
}
 
Enemy.prototype.update = function()
{
    this.drawX -= 7;
    if(this.drawX + this.width < 0)
    {
    this.drawX = Math.floor(Math.random() * gameWidth) + gameWidth;
    this.drawY = Math.floor(Math.random() * gameHeight);
    }
}
    
Enemy.prototype.destroy = function()
{
    enemies.splice(enemies.indexOf(this), 1);
}   
    
Player.prototype.draw = function()
{
    clearCtxPlayer();
    ctxPl.drawImage(tiles, this.srcX, this.srcY, this.width, this.height,
    this.drawX, this.drawY, this.width, this.height);
}
 
 
 
Player.prototype.update = function()
{
    
    if(this.drawX < 0) this.drawX = 0;
    if(this.drawX > gameWidth - this.width) this.drawX = gameWidth - this.width;
    if(this.drawY < 0) this.drawY = 0;
    if(this.drawY > gameHeight - this.height) this.drawY = gameHeight - this.height;
 
    for(var i = 0; i < enemies.length; i++)
    {
        if(this.drawX <= enemies[i].drawX + enemies[i].width &&
            this.drawX + this.width >= enemies[i].drawX  &&
            this.drawY + this.height >= enemies[i].drawY &&
            this.drawY <= enemies[i].drawY + enemies[i].height)
        {
            updateRestart();
        }
    }
    
    this.chooseDir();
}
 
 
Player.prototype.chooseDir = function()
{
    if(this.isUp)
        this.drawY -= this.speed;
    if(this.isDown)
        this.drawY += this.speed;
    if(this.isRight)
        this.drawX += this.speed;
    if(this.isLeft)
        this.drawX -= this.speed;
}
 
function checkKeyDown(e)
{
    var keyID = e.keyCode || e.which;
    var keyChar = String.fromCharCode(keyID);
    
    if(keyChar == "W")
    {
        player.isUp = true;
        e.preventDefault();
    }
    if(keyChar == "S")
    {
        player.isDown = true;
        e.preventDefault();
    }
    if(keyChar == "D")
    {
        player.isRight = true;
        e.preventDefault();
    }
    if(keyChar == "A")
    {
        player.isLeft = true;
        e.preventDefault();
    }
}
 
function checkKeyUp(e)
{
    var keyID = e.keyCode || e.which;
    var keyChar = String.fromCharCode(keyID);
    
    if(keyChar == "W")
    {
        player.isUp = false;
        e.preventDefault();
    }
    if(keyChar == "S")
    {
        player.isDown = false;
        e.preventDefault();
    }
    if(keyChar == "D")
    {
        player.isRight = false;
        e.preventDefault();
    }
    if(keyChar == "A")
    {
        player.isLeft = false;
        e.preventDefault();
    }
}
 
function drawRect()
{
    ctxMap.fillStyle = "green";
    ctxMap.fillRect(10, 10, 100, 100);
}
 
function clearRect()
{
    ctxMap.clearRect(0, 0, 800, 500);
}
 
function clearCtxPlayer()
{
    ctxPl.clearRect(0, 0, gameWidth, gameHeight);
}
 
function clearCtxEnemy()
{
    ctxEnemy.clearRect(0, 0, gameWidth, gameHeight);
}
 
function updateStats()
{
    ctxStats.clearRect(0, 0, gameWidth, gameHeight);
    ctxStats.fillText("Score: " + health, 10, 20);
}
 
function updateRestart()
{   
    ctxRestart.clearRect(0, 0, gameWidth, gameHeight);
    ctxRestart.fillText("RESTART ", 350, 250);
    stopLoop();
    shutdown = true;
}
 
function getClickXY(event)
  {      
    if ( shutdown !== true ) return;
    shutdown = false;
    //location.reload();
    init();
  }
  
function drawBg()
{
    ctxMap.clearRect(0, 0, gameWidth, gameHeight);
    ctxMap.drawImage(background, 0, 0, 800, 480,
    mapX, 0, gameWidth, gameHeight);
    ctxMap.drawImage(background1, 0, 0, 800, 480,
    map1X, 0, gameWidth, gameHeight);
}
 
 
 
 
 
window.onload = init;
 
})();
 
</script>
https://jsfiddle.net/wgb14m0e/10/
1
5 / 7 / 2
Регистрация: 06.04.2015
Сообщений: 62
04.04.2016, 23:23  [ТС] 7
Спасибо
В двух словах не расскажешь, что изменил в коде
вот про это интересно
Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var init_once_inc = 0;
function init_once() {
    if ( init_once_inc != 0 ) {
        return;
    }
    init_once_inc++;
    
    var drawBtn = document.getElementById("drawBtn");
    var clearBtn = document.getElementById("clearBtn");
    
    drawBtn.addEventListener("click", drawRect, false);
    clearBtn.addEventListener("click", clearRect, false);   
    
    document.addEventListener("keydown", checkKeyDown, false);
    document.addEventListener("keyup", checkKeyUp, false);  
    
    var restart = document.getElementById("restart");
    restart.addEventListener('click', getClickXY, false);   
}
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
04.04.2016, 23:23
Помогаю со студенческими работами здесь

Uncaught TypeError: Cannot read property 'elements' of undefined
Только начал изучать и сразу тормоз... оШИБКА: Uncaught TypeError: Cannot read property 'elements'...

Метод split - выдается ошибка Uncaught TypeError: Cannot read property 'split' of undefined
Вот кусок кода CheckLinkText: function(val, f){ if(!$('#attach_lnk_stared').val()){...

Как справиться с ошибкой в js : Uncaught TypeError: Cannot read property 'style' of undefined
Не понимаю как правильно описать действия со сменой значения display : &lt;script...

Ошибка при изменении стилей: Uncaught TypeError: Cannot read property 'style' of null
как поменять фоновый цвет у блока? я делаю вот так:...

Uncaught TypeError: Cannot read property 'addEventListener' of null
Приветствую всех, такая проблема: Пишу небольшой калькулятор стоимости определённого продукта. На...

Uncaught TypeError: Cannot read property 'className' of null
var ex = document.getElementById(&quot;exchanges&quot;); var end = document.getElementById(&quot;end&quot;); var re =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru