-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlab_07.html
More file actions
628 lines (586 loc) · 20.8 KB
/
lab_07.html
File metadata and controls
628 lines (586 loc) · 20.8 KB
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
<html>
<head>
<meta charset='utf-8'>
</head>
<body>
<canvas width='1000', height='1000', id='canvas_1'></canvas>
<script>
function Draw_Line(ctx, x0, y0, x1, y1, scale = 1)
{
let dy = Math.abs(y1-y0);
let dx = Math.abs(x1-x0);
let dmax = Math.max(dx,dy);
let dmin = Math.min(dx,dy);
let xdir = 1;
let ydir = 1;
if(x1<x0) xdir = -1;
if(y1<y0) ydir = -1;
let eps = 0;
let k = 2*dmin;
if(dy <= dx)
{
let y = y0;
for(let x=x0; x*xdir<=x1*xdir;x+=xdir)
{
ctx.fillRect(x,y,1*scale,1*scale);
eps = eps+k;
if(eps > dmax)
{
y += ydir;
eps = eps - 2*dmax;
}
}
}
else
{
let x = x0;
for(let y=y0; y*ydir<=y1*ydir;y+=ydir)
{
ctx.fillRect(x,y,1*scale,1*scale);
eps = eps+k;
if(eps > dmax)
{
x += xdir;
eps = eps - 2*dmax;
}
}
}
}
/*
* Класс для описания вектора / точки, имеет координаты x и y
*/
class Vertex
{
x = 0.0
y = 0.0
z = 0.0
constructor(x = 0.0, y = 0.0, z = 0.0)
{
this.x = x;
this.y = y;
this.z = z;
}
set_coordinates(x = 0.0,y = 0.0,z = 0.0)
{
this.x = x;
this.y = y;
this.z = z;
}
set_from_point(vec)
{
this.x = vec.x;
this.y = vec.y;
this.z = vec.z;
}
multiply_num(num)
{
this.x *= num;
this.y *= num;
this.z *= num;
}
module()
{
return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2));
}
Equal(p2)
{
if((this.x == p2.x)&&(this.y == p2.y)&&(this.z == p2.z))
{
return true;
}
return false;
}
}
/*
* Функция скалярного умножения векторов, возвращает число
*/
function SMultiply(point_1,point_2)
{
return ((point_1.x*point_2.x) + (point_1.y*point_2.y) + (point_1.z*point_2.z));
}
/*
* Функция вычисления векторного произведения векторов, возвращает число
*/
function VMultiply(point_1,point_2)
{
let tetha = Math.acos(SMultiply(point_1,point_2).multiply_num(point_1.module()*point_2.module()));
return point_1.module()*point_2.module()*Math.sin(tetha);
}
/*
* Функция вычитания векторов, возвращает вектор
*/
function Subtraction(point_1 = new Vertex(),point_2 = new Vertex())
{
return new Vertex((point_1.x-point_2.x),(point_1.y-point_2.y),(point_1.z-point_2.z))
}
/*
* Функция сложения векторов, возвращает вектор
*/
function Add(point_1 = new Vertex(),point_2 = new Vertex())
{
return new Vertex((point_1.x + point_2.x), (point_1.y + point_2.y),(point_1.z + point_2.z))
}
/*
* Класс описывающий линию, имеет начало, конец и нормали
* V0 - начальная точка
* V1 - точка конца
* N - нормаль
* vec - пространственный вектор
* e_vec - пространственный единичный вектор
*/
class Line
{
t0 = 0
t1 = 1
V0 = new Vertex()
V1 = new Vertex()
N = new Vertex()
vec = new Vertex()
e_vec = new Vertex()
constructor(start = new Vertex(), end = new Vertex())
{
this.V0.set_from_point(start);
this.V1.set_from_point(end);
var temp = Subtraction(end, start);
this.vec.set_coordinates(temp.x,temp.y);
//console.log(Math.pow(temp.x,2) + Math.pow(temp.y,2)," | ",Math.sqrt(Math.pow(temp.x,2) + Math.pow(temp.y,2))); /// debug
this.e_vec.set_coordinates((temp.x/Math.sqrt(Math.pow(temp.x,2) + Math.pow(temp.y,2))), (temp.y/Math.sqrt(Math.pow(temp.x,2) + Math.pow(temp.y,2))));
}
set_coordinates(x0,y0,x1,y1,z0,z1)
{
this.V0.set_coordinates(x0,y0,z0);
this.V1.set_coordinates(x1,y1,z1);
var temp = Subtraction(this.V1, this.V0);
this.vec = temp;
//console.log(Math.pow(temp.x,2) + Math.pow(temp.y,2)," | ",Math.sqrt(Math.pow(temp.x,2) + Math.pow(temp.y,2))); /// debug
this.e_vec.set_coordinates((temp.x/Math.sqrt(Math.pow(temp.x,2) + Math.pow(temp.y,2))), (temp.y/Math.sqrt(Math.pow(temp.x,2) + Math.pow(temp.y,2))));
}
}
/*
* Класс, созданный для математического описания многоугольника
*
* Максимальные границы фигуры:
*
* Функции:
* - check() - проверяет многоугольник на выпулость
* - draw_polygon - функция для рисования полигона
* - end_polygon - функция завершения рисования полигона (если надобность нужна)
*/
class Polygon
{
begin_point = new Vertex() /// @param begin_point Параметр начальной точки рисования
last_point = new Vertex() /// @param end_point Параметр последней точки рисования (в конце принимает значение начатьной)
started = false /// @param started Начато ли рисование многоугольника
ended = false /// @param ended Завершено ли рисование многоугольника
edges = [] /// @param edges[] Грани, из которых состоит многоугольник
y_max = 0 /// @param y_max Максимальное значение по y многоуголника
y_min = 0 /// @param y_min Минимальное значение по y многоугольника
x_max = 0 /// @param x_max Максимальное значение по x многоуголника
y_max = 0 /// @param x_min Минимальное значение по x многоугольника
/*
* @brief Функция вычисления внутренней нормали к стороне многоугольника. Рекомендации: использовать в конце построения.
*/
compute_normals()
{
for(let index = 0; index < this.count_edges;index++)
{
let n = new Vertex((-1 * (this.edges[index].e_vec.y/(this.edges[index].e_vec.x + 0.000001))),1)
let vec;
if (index == (this.count_edges - 1))
{
vec = new Line(this.edges[index].V0,this.edges[0].V1);
}
else
{
vec = new Line(this.edges[index].V0,this.edges[index + 1].V1);
}
if (!(SMultiply(n,vec.vec) > 0))
{
n.multiply_num(-1);
}
this.edges[index].N = n;
//console.log(vec," | ",this.edges[index].N, " | ", n); // debug
}
}
/*
* @brief Функция проверки выпуклости многоугольника. Возвращает true, если многоугольник выпуклый, иначе - false.
*/
check()
{
let z = ((this.edges[this.count_edges - 1].V1.x - this.edges[this.count_edges - 1].V0.x)*((this.edges[0].V1.y - this.edges[0].V0.y))) - ((this.edges[this.count_edges - 1].V1.y - this.edges[this.count_edges - 1].V0.y)*((this.edges[0].V1.x - this.edges[0].V0.x)));
let zi = 0;
for(let index = 1; index < this.count_edges;index++)
{
zi = ((this.edges[index - 1].V1.x - this.edges[index - 1].V0.x)*((this.edges[index].V1.y - this.edges[index].V0.y))) - ((this.edges[index - 1].V1.y - this.edges[index - 1].V0.y)*((this.edges[index].V1.x - this.edges[index].V0.x)));
if(zi*z < 0)
{
alert("Многоугольник не выпуклый!");
location.reload(); // перезагрузка страницы, убрать если нужна другая реализация
return false;
}
}
return true;
}
print(ctx)
{
ctx.fillStyle = "#000000";
for(let index = 0; index < this.edges.length;++index)
{
Draw_Line(ctx, this.edges[index].V0.x, this.edges[index].V0.y, this.edges[index].V1.x, this.edges[index].V1.y);
}
}
sample_polygon_1(ctx)
{
this.edges.push(new Line(new Vertex(200,200),new Vertex(500,200)));
this.edges.push(new Line(new Vertex(500,200),new Vertex(350,400)));
this.edges.push(new Line(new Vertex(350,400),new Vertex(500,600)));
this.edges.push(new Line(new Vertex(500,600),new Vertex(200,600)));
this.edges.push(new Line(new Vertex(200,600),new Vertex(200,200)));
this.y_max = 600;
this.y_min = 200;
this.x_max = 500;
this.x_min = 200;
this.print(ctx);
this.ended = true;
}
sample_polygon_2(ctx, num)
{
this.edges.push(new Line(new Vertex(500,800), new Vertex(400,750)));
this.edges.push(new Line(new Vertex(400,750), new Vertex(400,650)));
this.edges.push(new Line(new Vertex(400,650), new Vertex(300,650)));
this.edges.push(new Line(new Vertex(300,650), new Vertex(250,700)));
this.edges.push(new Line(new Vertex(250,700), new Vertex(150,600)));
this.edges.push(new Line(new Vertex(150,600), new Vertex(300,200)));
this.edges.push(new Line(new Vertex(300,200), new Vertex(700,200)));
this.edges.push(new Line(new Vertex(700,200), new Vertex(950,600)));
this.edges.push(new Line(new Vertex(950,600), new Vertex(750,600)));
this.edges.push(new Line(new Vertex(750,600), new Vertex(700,500)));
this.edges.push(new Line(new Vertex(700,500), new Vertex(600,650)));
this.edges.push(new Line(new Vertex(600,650), new Vertex(550,650)));
this.edges.push(new Line(new Vertex(550,650), new Vertex(500,800)));
this.y_max = 800;
this.y_min = 200;
this.x_max = 950;
this.x_min = 150;
this.print(ctx);
this.ended = true;
}
draw_polygon(ctx,x,y)
{
if(!this.ended)
{
if(!this.started)
{
this.begin_point.x = x;
this.begin_point.y = y;
this.last_point.x = this.begin_point.x;
this.last_point.y = this.begin_point.y;
this.y_max = y;
this.y_min = y;
this.x_max = x;
this.x_min = x;
this.started = true;
}
else
{
// Если мы хотим соединить конец и начало, то проверяем на дистанцию, если x,y находятся на удалении 10 пикслей, то соединяем
if ((Math.abs(x - this.begin_point.x) < 20) && (Math.abs(y - this.begin_point.y) < 20))
{
Draw_Line(ctx,this.last_point.x,this.last_point.y,this.begin_point.x,this.begin_point.y);
this.edges.push(new Line(this.last_point,this.begin_point));
this.ended = true;
this.last_point.x = this.begin_point.x;
this.last_point.y = this.begin_point.y;
this.compute_normals();
}
else
{
Draw_Line(ctx,this.last_point.x,this.last_point.y,x,y);
this.edges.push(new Line(this.last_point,new Vertex(x,y)));
if (y > this.y_max)
{
this.y_max = y;
}
else if (y < this.y_min)
{
this.y_min = y;
}
if (x > this.x_max)
{
this.x_max = x;
}
else if (x < this.x_min)
{
this.x_min = x;
}
this.last_point.x = x;
this.last_point.y = y;
}
}
}
//console.log(this.begin_point.x,this.begin_point.y, " | ",this.last_point.x,this.last_point.y," | ",this.started, " | ",this.ended);
}
}
</script>
<script>
/*
Функция трассировки Суть: из точки (x_edge,y) пускается луч в направлении coef (true - право, false - лево)
Считается количество точек пересечения с остальными гранями. Если количество точек пересечения по модулю два
равно 0, то возвращается false, иначе - true.
*/
function trace(poly, idx, y, x_edge, coef = true)
{
let idxr = idx - 1;
if (idxr < 0)
idxr = poly.edges.length - 1;
let idxl = idx + 1;
if (idxl > poly.edges.length)
idxl = 0;
let arr = new Set();
for(let index = 0; index < poly.edges.length;++index)
{
if((index == idx) || (index == idxr) || (index == idxl))
continue;
let line = poly.edges[index];
if (coef)
{
if(x_edge <= line.V0.x || x_edge <= line.V1.x)
{
if(line.V0.y == line.V1.y)
{
if(line.V0.y == y)
{
if(line.V0.x > line.V1.x)
arr.add(line.V0.x);
else
arr.add(line.V1.x);
}
}
else if(line.V0.x == line.V1.x) // Если линия вертикальная, то ...
{
if((line.V0.y <= y && y <= line.V1.y) || (line.V0.y >= y && y >= line.V1.y))
arr.add(line.V1.x);
}
else
{
let x = line.V0.x + ((line.V1.x-line.V0.x)*(y-line.V0.y)/(line.V1.y-line.V0.y));
if((line.V0.x <= x && x <= line.V1.x) || (line.V0.x >= x && x >= line.V1.x))
arr.add(x);
}
}
}
else
{
if(x_edge >= line.V0.x || x_edge >= line.V1.x)
{
if(line.V0.y == line.V1.y)
{
if(line.V0.y == y)
{
if(line.V0.x > line.V1.x)
arr.add(line.V1.x);
else
arr.add(line.V0.x);
}
}
else if(line.V0.x == line.V1.x) // Если линия вертикальная, то ...
{
if((line.V0.y <= y && y <= line.V1.y) || (line.V0.y >= y && y >= line.V1.y))
arr.add(line.V1.x);
}
else
{
let x = line.V0.x + ((line.V1.x-line.V0.x)*(y-line.V0.y)/(line.V1.y-line.V0.y));
if((line.V0.x <= x && x <= line.V1.x) || (line.V0.x >= x && x >= line.V1.x))
arr.add(x);
}
}
}
}
if(arr.size % 2 != 0)
return true;
return false;
}
function find_cross_x(poly, idx, y)
{
let line = poly.edges[idx];
if((line.V0.y == line.V1.y && line.V0.x == line.V1.x) || (y == poly.y_min) || (y == poly.y_max))
return undefined;
if(line.V0.y == line.V1.y) // Если линия горизонтальная, то ...
{
let left = line.V0.x;
let right = line.V1.x;
if(line.V0.x > line.V1.x)
{
left = line.V1.x;
right = line.V0.x;
}
let x_arr = [];
if(line.V0.y == y)
{
if(trace(poly,idx,y,right,true))
x_arr.push(right);
if(trace(poly,idx,y,left,false))
x_arr.push(left);
}
if(x_arr.length > 0)
return x_arr;
}
else if(line.V0.x == line.V1.x) // Если линия вертикальная, то ...
{
if((line.V0.y <= y && y <= line.V1.y) || (line.V0.y >= y && y >= line.V1.y))
return line.V0.x;
}
else // Иначе ...
{
if((line.V0.y == y) || (line.V1.y == y))
{
let num = idx - 1;
if (num < 0)
num = poly.edges.length - 1;
if(poly.edges[num].V0.y == y && poly.edges[num].V1.y == y)
return undefined;
if(poly.edges[num].V0.y == y)
{
if(line.V0.y == y)
{
if((poly.edges[num].V1.y > y && line.V1.y > y) || (poly.edges[num].V1.y < y && line.V1.y < y))
return undefined;
}
else
{
if((poly.edges[num].V1.y > y && line.V0.y > y) || (poly.edges[num].V1.y < y && line.V0.y < y))
return undefined;
}
}
else if(poly.edges[num].V1.y == y)
{
if(line.V0.y == y)
{
if((poly.edges[num].V0.y > y && line.V1.y > y) || (poly.edges[num].V0.y < y && line.V1.y < y))
return undefined;
}
else
{
if((poly.edges[num].V0.y > y && line.V0.y > y) || (poly.edges[num].V0.y < y && line.V0.y < y))
return undefined;
}
}
num = idx + 1;
if (num >= poly.edges.length)
num = 0;
if(poly.edges[num].V0.y == y && poly.edges[num].V1.y == y)
return undefined;
if(poly.edges[num].V0.y == y)
{
if(line.V0.y == y)
{
if((poly.edges[num].V1.y > y && line.V1.y > y) || (poly.edges[num].V1.y < y && line.V1.y < y))
return undefined;
}
else
{
if((poly.edges[num].V1.y > y && line.V0.y > y) || (poly.edges[num].V1.y < y && line.V0.y < y))
return undefined;
}
}
else if(poly.edges[num].V1.y == y)
{
if(line.V0.y == y)
{
if((poly.edges[num].V0.y > y && line.V1.y > y) || (poly.edges[num].V0.y < y && line.V1.y < y))
return undefined;
}
else
{
if((poly.edges[num].V0.y > y && line.V0.y > y) || (poly.edges[num].V0.y < y && line.V0.y < y))
return undefined;
}
}
}
let x = line.V0.x + ((line.V1.x-line.V0.x)*(y-line.V0.y)/(line.V1.y-line.V0.y));
if((line.V0.x <= x && x <= line.V1.x) || (line.V0.x >= x && x >= line.V1.x))
return x;
}
return undefined;
}
function cross(poly, y)
{
let x_arr = new Set();
for(let index = 0; index < poly.edges.length;++index)
{
let x = find_cross_x(poly, index, y);
if (x != undefined)
{
if(typeof x == "number")
x_arr.add(x);
else
for(let i = 0; i < x.length; ++i)
{
x_arr.add(x[i]);
}
}
}
return x_arr;
}
</script>
<script>
var canvas = document.getElementById('canvas_1');
var ctx = canvas.getContext('2d');
let x = 10;
let y = 10;
let poly = new Polygon();
let step = 10;
function compareNumeric(a, b) {
if (a > b) return 1;
if (a == b) return 0;
if (a < b) return -1;
}
canvas.addEventListener('click',function(e){
if (!poly.ended) // В начале рисуем многоугольник
{
poly.draw_polygon(ctx,e.offsetX,e.offsetY);
}
else
{
// Простая проверка на границы
if (((e.offsetX < poly.x_max)&&(e.offsetX > poly.x_min)) && ((e.offsetY < poly.y_max)&&(e.offsetY > poly.y_min)))
{
let dy = poly.y_max - e.offsetY;
let k = dy/step;
k = k - Math.floor(k);
let min_edge = poly.y_max - k*step;
ctx.fillStyle = getRandomColor();
for (let y = min_edge; y >= poly.y_min; y = y - step)
{
let x_arr = Array.from(cross(poly, y));
x_arr.sort(compareNumeric);
scale = 1;
for(let idx = 1; idx < x_arr.length; idx+=2)
{
Draw_Line(ctx,x_arr[idx-1], y, x_arr[idx], y);
}
}
poly.print(ctx);
}
else
{
alert("Точка вне зоны многоугольника!");
}
}
});
</script>
<script>
function getRandomColor()
{
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++)
{
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</body>
</html>