Форум программистов, компьютерный форум, киберфорум
HTML, CSS
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/11: Рейтинг темы: голосов - 11, средняя оценка - 5.00
1 / 9 / 0
Регистрация: 10.06.2017
Сообщений: 162

Показывает ошибку в строке 9. Uncaught TypeError: Cannot read property 'getContext' of null at change.html:9

10.12.2017, 06:31. Показов 2085. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
HTML5
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
<!DOCTYPE html>
<html>
<head>
    
</head>
<body>
    <script type = "text/javascript">
    var c = document.getElementById('canv');
var ctx = c.getContext('2d');
var width = c.width;
var height = c.height;
var shipx = 100;
var shipy = 100;
var ship_w = 70;//ширина корабля
var ship_h = 15;//высота
var r_border = width - ship_w;//правая граница экрана, далее по аналогии
var l_border = 0;
var t_border = ship_h;
var b_border = height;
var bgr = new Array;//массив для фоновых объектов
var bullets = new Array;
var enemies = new Array;
 
var k_down = 0;
var k_up = 0;
var k_left = 0;
var k_right = 0;
var fires = 0;//стреляет ли корабль
//векторы движения корабля
var vx = 0; 
var vy = 0;
 
var cyclestep = 0;
var game_over = 0;
var score = 0;
var cset = 0;//флаг установки куков
function enemy(hp,dx,dy,type,x,y,width){ //класс враг
        this.hp = hp;
        this.type = type;
        this.x = x;
        this.y = y;
        this.width = width;
        this.hwidth = width/2;
        this.dx = dx;
        this.dy = dy;
}
function bgObj(x,y,speed){ //класс фоновый объект
    this.x = x;
    this.y = y;
    this.speed = speed;
}
function bullet(x,y){ //класс пуля
    this.x = x;
    this.y = y;
    this.dx = 12;
    this.dy = 0;
}
function setCookie(name,value){
    var d = new Date();
    d.setDate(d.getDate()+1);
    document.cookie = name + "="+ escape(value)+";expires="+d.toGMTString();
}
function draw(){
    //устанавливаем векторы движения
    if (k_left) vx -= 2;
    else if (k_right) vx +=2;
    if (k_up) vy -=4;
    else if (k_down) vy +=4;    
    //предел скорости
    if(vx > 7) vx = 7;
    if(vy > 5) vy = 5;
    if (vy < -5) vy = -5;
    if (vx < -5) vx = -5;   
    //стреляем
    if (fires == 1 && cyclestep % 8 == 0 && game_over != 1){
            var b = new bullet(shipx+74,shipy-14);
            bullets.push(b);
    }       
    draw_bg();
    shoot();
    if (game_over != 1) draw_ship();    
    move_ship();
    draw_enemies();
    enemy_ai(); 
    if(game_over == 1){
        ctx.fillStyle = "rgb(72,118,255)";
        ctx.font = "bold 30px Arial";
        ctx.textBaseline = "top";
        ctx.fillText("GAME OVER",130,150);      
        if(cset != 1){
        var uname = prompt('Enter your name:','player');
        if (uname == null || uname == "") uname = 'player';         
        setCookie('username',uname);
        setCookie('score',score);
        cset = 1;
        }
    }   
    cyclestep++;
    if (cyclestep == 128) make_wave(1,4,30);
    if (cyclestep == 256){
    cyclestep = 0;
    make_wave(2,4,20);
    }
}
function draw_bg(){
    var distance; //"дальние" звезды более тусклые
    ctx.fillStyle = "rgb(0,0,0)";
    ctx.fillRect(0,0,width,height); 
    for (var i = 0; i < bgr.length; i++){
        distance = bgr[i].speed*40;
        if (distance < 100) distance = 100; //но не слишком 
        ctx.fillStyle = "rgb("+distance+","+distance+","+distance+")"; //цвет, как вы видите - градиент серого
        ctx.fillRect(bgr[i].x, bgr[i].y,1,1);
        bgr[i].x -=bgr[i].speed;
        if (bgr[i].x < 0){ //если звезда зашла за пределы экрана, отрисовываем заново (с другими координатами)
            bgr[i].x += width;
            bgr[i].y = Math.floor(Math.random() * height);
            bgr[i].speed = Math.floor (Math.random() * 4) + 1;
        }
    }
}
for (var i = 1; i < 50; i++){
    var b = new bgObj(Math.floor(Math.random()*height),Math.floor(Math.random()*width),Math.floor(Math.random()*4)+1);
    bgr.push(b);
    }
setInterval("draw();", 40);
function draw_ship(){
    //Тело
    var sbpaint = ctx.createLinearGradient(shipx,shipy,shipx,shipy-15);//градиент
    sbpaint.addColorStop(0,'rgb(220,220,230)');
    sbpaint.addColorStop(1,'rgb(170,170,180)');
    ctx.fillStyle = sbpaint;
    ctx.beginPath();
    ctx.moveTo(shipx,shipy);
    ctx.lineTo(shipx+60,shipy);
    ctx.lineTo(shipx+50,shipy-15);
    ctx.lineTo(shipx+10,shipy-15);
    ctx.lineTo(shipx,shipy);
    ctx.fill();
    //Пушка
    var gpaint = ctx.createLinearGradient(shipx+50,shipy-12,shipx+70,shipy-12);
    gpaint.addColorStop(0,'rgb(190,190,200)');
    gpaint.addColorStop(1,'rgb(120,120,130)');
    ctx.fillStyle = gpaint;
    ctx.beginPath();
    ctx.moveTo(shipx+50,shipy-13);
    ctx.lineTo(shipx+70,shipy-13);
    ctx.lineTo(shipx+70,shipy-8);
    ctx.lineTo(shipx+50,shipy-8);
    ctx.lineTo(shipx+50,shipy-13);
    ctx.fill(); 
    //отображаем очки
    ctx.fillStyle = "rgb(58,95,205)";
    ctx.font = "14px Arial";
    ctx.textBaseline = "top";
    ctx.fillText("Score:"+score,3,3);
}
function move_ship(){//двигаем корабль - без комментариев
    shipx += vx;
    shipy +=vy; 
    if (shipx>r_border){
    shipx = r_border; 
    vx = 0;
    }
    if (shipx<l_border){ 
    shipx = l_border;
    vx = 0;
    }
    if (shipy>b_border){
    shipy = b_border;
    vy = 0;
    }
    if (shipy<t_border){
    shipy = t_border;
    vy = 0;
    }
}
function shoot(){
    var dead_bullets = new Array;
 
        for (var i = 0; i < bullets.length; i++) {
            ctx.fillStyle = "rgb(173,216,230)";
            ctx.fillRect(bullets[i].x,bullets[i].y,12,2);//пули прямоугольные, 12х2
        //проверяем выход за пределы экрана
        if (bullets[i].x > width) dead_bullets.push(i);
        //проверяем столкновение с врагом
        for (var j = 0;j < enemies.length;j++){
            if (enemies[j].type > 0){
                if (bullets[i].x >= enemies[j].x-enemies[j].hwidth && bullets[i].x < enemies[j].x+enemies[j].hwidth && bullets[i].y >= enemies[j].y-enemies[j].hwidth && bullets[i].y < enemies[j].y+enemies[j].hwidth){
                    enemies[j].hp--;
                }
                if(enemies[j].hp < 0){ 
                enemies[j].type = -1;
                }
            }
        }   
    bullets[i].x += bullets[i].dx;
    bullets[i].y += bullets[i].dy;
        }
    //убираем "мертвые" пули
    for (var i = dead_bullets.length-1; i >= 0; i--){
        bullets.splice(dead_bullets[i],1);
    }
}
function make_wave(type,count,ewidth){
var h = Math.floor(Math.random()*(height-40))+40;
 
    for (var i = 0;i < count;i++){
        var n = new enemy(2,Math.floor(Math.random()* -4)-1,0,type,width+i*20,h+i*21,ewidth);
        enemies.push(n);
        }
}
function draw_enemies(){
    var dead_bad = new Array;
    for (var i = 1;i < enemies.length; i++){
        //Тип 1 - Полупрозрачный загадочный круг
        if(enemies[i].type == 1){
                var rg = ctx.createRadialGradient(enemies[i].x,enemies[i].y,0,enemies[i].x,enemies[i].y,enemies[i].hwidth);
                rg.addColorStop(0,"rgba(130,130,130,0.4)");
                rg.addColorStop(0.5,"rgba(125,125,125,0.5)");
                rg.addColorStop(1,"rgba(120,120,120,"+enemies[i].hp*0.4+")");               
                ctx.fillStyle = rg;
                ctx.beginPath();
                ctx.arc(enemies[i].x,enemies[i].y,15,0,Math.PI*2,true);
                ctx.fill();
        }
        //Тип 2 - Треугольник
        if(enemies[i].type == 2){
            var rg = ctx.createRadialGradient(enemies[i].x+10,enemies[i].y-10,0,enemies[i].x+10,enemies[i].y-10,enemies[i].width);
            rg.addColorStop(0,"rgba(240,240,0,"+enemies[i].hp*0.4+")");
            rg.addColorStop(1,"rgba(240,240,0,0.6");            
            ctx.fillStyle = rg;
            ctx.beginPath();
            ctx.moveTo(enemies[i].x,enemies[i].y);
            ctx.lineTo(enemies[i].x+10,enemies[i].y-20);
            ctx.lineTo(enemies[i].x+20,enemies[i].y);
            ctx.lineTo(enemies[i].x,enemies[i].y);
            ctx.fill();
        }
        //Бабах! Взрыв
        if(enemies[i].type < 0){
            ctx.fillStyle="rgb(250,250,250)";
            ctx.beginPath();
            ctx.arc(enemies[i].x,enemies[i].y,enemies[i].type * -4,0,Math.PI*2,true);
            ctx.fill();
        }
    if(enemies[i].type < 0) enemies[i].type--;
    if(enemies[i].type < -4){
    dead_bad.push(i);
    score+=2;
    }   
    if(enemies[i].x + enemies[i].width < 0) dead_bad.push(i);   
    if(enemies[i].y + 5 < 0) dead_bad.push(i);  
    if(enemies[i].y  > height+enemies[i].width) dead_bad.push(i);   
    if(enemies[i].x < shipx+60 && enemies[i].x > shipx && enemies[i].y < shipy+15 && enemies[i].y > shipy) game_over = 1;   
    enemies[i].x += enemies[i].dx;
    enemies[i].y += enemies[i].dy;
    }
    for (var i = 0;i < dead_bad.length;i++){
        enemies.splice(dead_bad[i],1);
    }
}
function enemy_ai(){
    for (var i = 0;i < enemies.length;i++){
        if(enemies[i].type == 2){
            if(cyclestep % 4 == 0){
                if(shipy > enemies[i].y && enemies[i].y+20 < height && enemies[i].dy < 4 && enemies[i].x < width-100) enemies[i].dy++;
                if(shipy < enemies[i].y && enemies[i].y-20 > 0 && enemies[i].dy > -4 && enemies[i].x < width-100) enemies[i].dy--;
            }
        }
    }
}
function get_key_down(e){
    if (e.keyCode == 37) k_left = 1;
    if (e.keyCode == 38) k_up = 1;
    if (e.keyCode == 39) k_right = 1;
    if (e.keyCode == 40) k_down = 1;    
    if(e.keyCode == 32) fires = 1;
}
function get_key_up(e){
    if (e.keyCode == 37) k_left = 0;
    if (e.keyCode == 38) k_up = 0;
    if (e.keyCode == 39) k_right = 0;
    if (e.keyCode == 40) k_down = 0;    
    if(e.keyCode == 32) fires = 0;
}
</script>
</body>
</html>
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
10.12.2017, 06:31
Ответы с готовыми решениями:

Uncaught TypeError: Cannot read property 'html' of null
Выдает ошибку - function getvalues () { $.post(&quot;/autoisk/getvalues.php&quot;,{ name:selectedcompany , summma:...

Выдает ошибку Uncaught TypeError: Cannot read property 'appendChild' of null at HTMLButtonElement.addDeveloper
Как победить ошибку Uncaught TypeError: Cannot read property 'appendChild' of null at HTMLButtonElement.addDeveloper. ...

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

1
Тутошний я
 Аватар для Grey
2147 / 1202 / 225
Регистрация: 03.11.2009
Сообщений: 4,424
Записей в блоге: 2
10.12.2017, 18:41
а где элемент с id canv ?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
10.12.2017, 18:41
Помогаю со студенческими работами здесь

Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
как вылечить такую ошибку? Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

Uncaught TypeError: Cannot read property 'innerHTML' of null
Ошибка в работе кода: &lt;script type='text/JavaScript'&gt; function verocultar(cual) { ...

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

Uncaught TypeError: Cannot read property 'style' of null
Доброго времени суток! Есть список, и две кнопки, по нажатию на одну из них список уезжает влево и прозрачность становится 0, при нажатии...

Uncaught TypeError: Cannot read property 'addEventListener' of null
В чем ошибка и как исправить?


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

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Автоматическое создание документа при проведении другого документа
Maks 29.03.2026
Реализация из решения ниже выполнена на нетиповых документах, разработанных в конфигурации КА2. Есть нетиповой документ "ЗаявкаНаРемонтСпецтехники" и нетиповой документ "ПланированиеСпецтехники". В. . .
Настройка движения справочника по регистру сведений
Maks 29.03.2026
Решение ниже реализовано на примере нетипового справочника "ТарифыМобильнойСвязи" разработанного в конфигурации КА2, с целью учета корпоративной мобильной связи в коммерческом предприятии. . . .
Автозаполнение реквизита при выборе элемента справочника
Maks 27.03.2026
Программный код из решения ниже на примере нетипового документа "ЗаявкаНаРемонтСпецтехники" разработанного в конфигурации КА2. При выборе "Спецтехники" (Тип Справочник. Спецтехника), заполняется. . .
Сумматор с применением элементов трёх состояний.
Hrethgir 26.03.2026
Тут. https:/ / fips. ru/ EGD/ ab3c85c8-836d-4866-871b-c2f0c5d77fbc Первый документ красиво выглядит, но без схемы. Это конечно не даёт никаких плюсов автору, но тем не менее. . . всё может быть. . .
Автозаполнение реквизитов при создании документа
Maks 26.03.2026
Программный код из решения ниже размещается в модуле объекта документа, в процедуре "ПриСозданииНаСервере". Алгоритм проверки заполнения реализован для исключения перезаписи значения реквизита,. . .
Команды формы и диалоговое окно
Maks 26.03.2026
1. Команда формы "ЗаполнитьЗапчасти". Программный код из решения ниже на примере нетипового документа "ЗаявкаНаРемонтСпецтехники" разработанного в конфигурации КА2. В качестве источника данных. . .
Кому нужен AOT?
DevAlt 26.03.2026
Решил сделать простой ланчер Написал заготовку: dotnet new console --aot -o UrlHandler var items = args. Split(":"); var tag = items; var id = items; var executable = args;. . .
Отправка уведомления на почту при создании или изменении элементов справочника
Maks 24.03.2026
Программная отправка письма электронной почты на примере типового справочника "Склады" в конфигурации БП3. Перед реализацией необходимо выполнить настройку системной учетной записи электронной. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru