Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Javascript GIF.js Project to Record Screen and Download it as GIF Animation File in Browser Using HTML5

Posted on November 15, 2022

 

 

Welcome folks today in this blog post we will be talking about how to record screen using gif.js library and download it as gif animation file in browser using html5. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
 
<head>
  <title>gifcap</title>
  <link href='https://fonts.googleapis.com/css?family=Baloo+2:700' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
  <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/2.0.4/mithril.min.js"
    integrity="sha256-8cl9GQUonfQFzoyXWdf5ZsGnUJ/FC8PE6E7E9U6JE30=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gif.js/0.2.0/gif.js"
    integrity="sha256-qLERBxuzsSPDAuYYLAHWs1UPk6S2JzmLB8RoddhAkLs=" crossorigin="anonymous"></script>
</head>
 
<body>
  <header id="app-header">
    <h1><span class="gif">gif</span><span class="cap">cap</span></h1>
  </header>
  <section id="app-container"></section>
  <script src='main.js'></script>
</body>
</html>

 

 

As you can see we are copy paste the above html code. Also here as you can see we are including the gif.js cdn which is the gif animation encoder. And also we are including the mithrill cdn also

 

 

Adding the CSS Stylesheet

 

 

Now we need to copy paste the css code to style the app  as well. So this is the css code you need to copy paste below

 

 

style.css

 

 

CSS
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
@import url('https://unpkg.com/chota@0.7.1');
 
:root {
  --color-primary: #AD2C2C;
  --color-lightGrey: #d2d6dd;
  --color-grey: #5e5e5e;
  --color-darkGrey: #3f4144;
  --color-error: #d43939;
  --color-success: #28bd14;
  --grid-maxWidth: 120rem;
  --grid-gutter: 2rem;
  --font-size: 1.6rem;
  --font-family: 'Roboto', sans-serif;
}
 
html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
 
body {
  display: flex;
  flex-direction: column;
  color: #333;
}
 
img {
  max-width: initial !important;
}
 
.hidden {
  display: none;
}
 
#app-header {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
 
#app-footer {
  display: flex;
  justify-content: space-between;
  padding: 1em;
  background: #333333;
  color: #c5c5c5;
  border-top: 1px solid #9e9e9e;
  font-size: 0.8em;
}
 
#app-footer a {
  color: #ce6464;
}
 
#app-footer img {
  vertical-align: middle;
}
 
h1 {
  font-family: 'Baloo 2', cursive;
  font-size: 5em;
}
 
.gif {
  color: #AD2C2C;
}
 
.cap {
  color: #2E2E2E;
}
 
.button {
  display: flex;
  box-shadow: 0px 0px 5px 0px #00000054;
}
 
.button:active {
  box-shadow: 0px 0px 3px 0px #00000054;
}
 
button:not(.icon-only) > img {
  margin-right: 0.3em;
}
 
.actions {
  padding: 2em;
  display: flex;
  border-top: 1px solid #9e9e9e;
}
 
.actions:empty {
  display: none;
}
 
.status {
  display: flex;
  justify-content: center;
}
 
#app-container {
  flex: 1;
}
 
.view {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
 
.content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  box-shadow: inset 0 0 4px #a5a5a5;
  border-top: 1px solid #9e9e9e;
  font-size: 20px;
  text-align: center;
  background: #fafafa;
  position: relative;
  overflow: hidden;
}
 
.recording, .preview {
  box-shadow: 0px 0px 5px 1px #00000054;
}
 
.recording {
  max-width: 90vw;
  max-height: 90vh;
  display: block;
}
 
.preview {
  position: absolute;
}
 
.preview > canvas,
.preview > .crop-box {
  position: absolute;
  top: 0;
  left: 0;
}
 
.preview > canvas {
  width: 100%;
  height: 100%;
}
 
.recording-card > footer {
  border-top: 1px solid #9e9e9e;
  margin-top: 18px;
  padding-top: 10px;
  display: flex;
  justify-content: space-between;
}
 
.tag, .tag > a {
  display: flex;
  align-items: center;
}
 
.tag img {
  margin-right: 0.3em;
}
 
.crop {
  cursor: crosshair;
}
 
.crop-box {
  position: absolute;
  background: rgba(193, 193, 193, 0.69);
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
 
.playbar {
  flex: 1;
  margin: 0 10px;
  position: relative;
}
 
.playbar > input {
  height: 50%;
  margin: 0;
}
 
.playbar > input:disabled {
  opacity: 1;
}
 
.playbar > .trim-bar {
  border-top: 2px solid #AD2C2C;
  position: absolute;
  top: calc(50% + 4px);
}
 
.playbar > .trim-bar > .trim-start,
.playbar > .trim-bar > .trim-end {
  position: absolute;
  border: 6px solid #AD2C2C;
  border-bottom-color: transparent;
  cursor: pointer;
}
 
.playbar > .trim-bar > .trim-start {
  top: 0;
  left: 0;
  border-right-color: transparent;
}
 
.playbar > .trim-bar > .trim-end {
  top: 0;
  right: 0;
  border-left-color: transparent;
}
 
input[type="range"] {
  padding-left: 0 !important;
  padding-right: 0 !important;
}
 
.button.outline {
  border: none;
}

 

 

 

 

 

As you can see we have the start recording button where the user can record the screen and convert it as gif animation and share it on social media websites. Here the data is not uploaded to the server. Only recording is done at the client side.

 

 

Now we need to make the main.js file and copy paste the following code. This will be the javascript code which is required for this application

 

 

main.js

 

 

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
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
const FPS = 10;
const FRAME_DELAY = Math.floor(1000 / FPS);
 
function timediff(millis) {
  const abs = Math.floor(millis / 1000);
  const mins = Math.floor(abs / 60);
  const secs = abs % 60;
  const s = `${secs < 10 ? '0' : ''}${secs}`;
  const m = mins > 0 ? `${mins < 10 ? '0' : ''}${mins}` : '00';
  return `${m}:${s}`;
}
 
function humanSize(size) {
  if (size < 1024) {
    return '1 KB';
  }
 
  size = Math.round(size / 1024);
  return size < 1024 ? `${size} KB` : `${Math.floor(size / 1024 * 100) / 100} MB`;
}
 
const Button = {
  view(vnode) {
    return m('button', {
      class: `button ${vnode.attrs.primary ? 'primary' : 'secondary'} ${vnode.attrs.label ? '' : 'icon-only'} ${vnode.attrs.outline ? 'outline' : ''}`,
      onclick: vnode.attrs.onclick,
      title: vnode.attrs.title || vnode.attrs.label,
      disabled: vnode.attrs.disabled
    }, [
      m('img', { src: `https://icongr.am/${vnode.attrs.iconset || 'octicons'}/${vnode.attrs.icon}.svg?size=16&color=${vnode.attrs.outline ? '333333' : 'ffffff'}` }),
      vnode.attrs.label
    ]);
  }
};
 
const Timer = {
  view(vnode) {
    return m('span.tag.is-small', [
      m('img', { src: 'https://icongr.am/octicons/clock.svg?size=16&color=333333' }),
      timediff(vnode.attrs.duration)
    ]);
  }
};
 
const View = {
  view(vnode) {
    return m('section', { class: 'view' }, [
      m('section', { class: `content ${vnode.attrs.contentClass || ''}`, ...(vnode.attrs.contentProps || {}) }, vnode.children),
      m('section', { class: 'actions' }, vnode.attrs.actions)
    ]);
  }
};
 
 
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
 
class IdleView {
 
  constructor(vnode) {
    this.app = vnode.attrs.app;
  }
 
  view() {
    let content, actions;
 
    if (this.app.recording) {
      content = m('.recording-card', [
        m('a', { href: this.app.recording.url, target: '_blank' }, [
          m('img.recording', { src: this.app.recording.url })
        ]),
        m('footer', [
          m(Timer, { duration: this.app.recording.duration }),
          m('span.tag.is-small', [
            m('a.recording-detail', { href: this.app.recording.url, target: '_blank' }, [
              m('img', { src: 'https://icongr.am/octicons/cloud-download.svg?size=16&color=333333' }),
              humanSize(this.app.recording.size)
            ])
          ]),
        ]),
      ]);
 
      actions = [
        m(Button, { label: 'Start Recording', icon: 'play', onclick: () => this.app.startRecording(), primary: true }),
        m(Button, { label: 'Discard', icon: 'trashcan', onclick: () => this.app.cancel() })
      ];
    } else {
      content = [
        m('p', 'Create animated GIFs from a screen recording.'),
        m('p', 'Client-side only, no data is uploaded. Modern browser required.'),
        isMobile ? m('p', 'Sorry, mobile does not support screen recording.') : undefined,
        isMobile ? undefined : m(Button, { label: 'Start Recording', icon: 'play', onclick: () => this.app.startRecording(), primary: true }),
      ];
    }
 
    return [m(View, { actions }, content)];
  }
}
 
class RecordView {
 
  constructor(vnode) {
    this.app = vnode.attrs.app;
    this.recording = this.app.recording;
    this.startTime = undefined;
  }
 
  async oncreate(vnode) {
    const video = vnode.dom.getElementsByTagName('video')[0];
    const canvas = vnode.dom.getElementsByTagName('canvas')[0];
 
    let captureStream;
 
    try {
      captureStream = await navigator.mediaDevices.getDisplayMedia({ video: true });
    } catch (err) {
      console.error(err);
      this.app.cancel();
      m.redraw();
      return;
    }
 
    video.srcObject = captureStream;
 
    const ctx = canvas.getContext('2d');
 
    const frameInterval = setInterval(() => {
      if (video.videoWidth === 0) {
        return;
      }
 
      const first = typeof this.startTime === 'undefined';
 
      if (first) {
        const width = video.videoWidth;
        const height = video.videoHeight;
 
        this.startTime = new Date().getTime();
        this.recording.width = width;
        this.recording.height = height;
        canvas.width = `${width}`;
        canvas.height = `${height}`;
      }
 
      ctx.drawImage(video, 0, 0);
 
      this.recording.frames.push(ctx.getImageData(0, 0, this.recording.width, this.recording.height));
    }, FRAME_DELAY);
 
    const redrawInterval = setInterval(() => m.redraw(), 1000);
 
    const track = captureStream.getVideoTracks()[0];
    const endedListener = () => {
      this.app.stopRecording();
      m.redraw();
    };
    track.addEventListener('ended', endedListener);
 
    this.onbeforeremove = () => {
      clearInterval(frameInterval);
      clearInterval(redrawInterval);
      track.removeEventListener('ended', endedListener);
      track.stop();
    };
 
    m.redraw();
  }
 
  view() {
    const actions = [
      m(Button, { label: 'Stop', icon: 'primitive-square', onclick: () => this.app.stopRecording() })
    ];
 
    return [
      m(View, { actions }, [
        m(Timer, { duration: typeof this.startTime === 'number' ? new Date().getTime() - this.startTime : 0 }),
        m('canvas.hidden', { width: 640, height: 480 }),
        m('video.hidden', { autoplay: true, playsinline: true }),
      ]),
    ];
  }
}
 
class PreviewView {
 
  constructor(vnode) {
    this.app = vnode.attrs.app;
    this.recording = this.app.recording;
    this.canvas = undefined;
    this.playbar = undefined;
    this.content = undefined;
 
    this.viewportDisposable = undefined;
    this.viewport = {
      width: undefined,
      height: undefined,
      top: 0,
      left: 0,
      zoom: 1
    };
 
    this.playback = {
      index: undefined,
      disposable: undefined,
      reset: false
    };
 
    this.trim = {
      start: 0,
      end: this.recording.frames.length - 1
    };
 
    this.crop = {
      top: 0,
      left: 0,
      width: this.recording.width,
      height: this.recording.height
    };
  }
 
  get isPlaying() { return !!this.playback.disposable; }
 
  oncreate(vnode) {
    this.canvas = vnode.dom.getElementsByTagName('canvas')[0];
    this.playbar = vnode.dom.querySelector('.playbar');
    this.content = vnode.dom.querySelector('.content');
 
    const viewportListener = () => this.updateViewport();
    window.addEventListener('resize', viewportListener);
    this.viewportDisposable = () => window.removeEventListener('resize', viewportListener);
    this.updateViewport();
    this.zoomToFit();
 
    m.redraw(); // prevent flickering
    setTimeout(() => this.play());
  }
 
  zoomToFit() {
    this.viewport.zoom = Math.max(0.1, Math.min(1, this.viewport.width * .95 / this.recording.width, this.viewport.height * .95 / this.recording.height));
  }
 
  updateViewport() {
    this.viewport.width = Math.floor(this.content.clientWidth);
    this.viewport.height = Math.floor(this.content.clientHeight);
  }
 
  onbeforeremove() {
    this.pause();
    this.viewportDisposable();
  }
 
  view() {
    const isCropped = this.crop.top !== 0 || this.crop.left !== 0 || this.crop.width !== this.recording.width || this.crop.height !== this.recording.height;
    const actions = [
      m(Button, { title: this.isPlaying ? 'Pause' : 'Play', iconset: 'material', icon: this.isPlaying ? 'pause' : 'play', primary: true, onclick: () => this.togglePlayPause() }),
      m('.playbar', [
        m('input', { type: 'range', min: 0, max: `${this.recording.frames.length - 1}`, value: `${this.playback.index}`, disabled: this.isPlaying, oninput: e => this.onPlaybarInput(e) }),
        m('.trim-bar', { style: { left: `${this.trim.start * 100 / (this.recording.frames.length - 1)}%`, width: `${(this.trim.end - this.trim.start) * 100 / (this.recording.frames.length - 1)}%` } }, [
          m('.trim-start', { onmousedown: e => this.onTrimMouseDown('start', e) }),
          m('.trim-end', { onmousedown: e => this.onTrimMouseDown('end', e) }),
        ])
      ]),
      m(Button, { title: 'Discard', icon: 'trashcan', onclick: () => this.app.cancel() }),
      m(Button, { label: 'Render', icon: 'gear', onclick: () => this.app.startRendering({ trim: this.trim, crop: this.crop }), primary: true }),
    ];
 
    const scale = value => value * this.viewport.zoom;
    const width = scale(this.recording.width);
    const height = scale(this.recording.height);
    const top = Math.floor(scale(this.viewport.top) + (this.viewport.height / 2) - (height / 2));
    const left = Math.floor(scale(this.viewport.left) + (this.viewport.width / 2) - (width / 2));
 
    return [
      m(View, {
        actions,
        contentClass: 'crop',
        contentProps: {
          onwheel: e => this.onContentWheel(e),
          onmousedown: e => this.onContentMouseDown(e),
          oncontextmenu: e => e.preventDefault()
        }
      }, [
        m('.preview', { style: { top: `${top}px`, left: `${left}px`, width: `${width}px`, height: `${height}px` } }, [
          m('canvas', { width: this.recording.width, height: this.recording.height }),
          isCropped && m('.crop-box', {
            style: {
              // here be dragons!
              clipPath: `polygon(evenodd, 0 0, 0 ${scale(this.recording.height)}px, ${scale(this.recording.width)}% ${scale(this.recording.height)}px, ${scale(this.recording.width)}% 0, 0 0, ${scale(this.crop.left)}px ${scale(this.crop.top)}px, ${scale(this.crop.left)}px ${scale(this.crop.top + this.crop.height)}px, ${scale(this.crop.left + this.crop.width)}px ${scale(this.crop.top + this.crop.height)}px, ${scale(this.crop.left + this.crop.width)}px ${scale(this.crop.top)}px, ${scale(this.crop.left)}px ${scale(this.crop.top)}px)`
            }
          })
        ]),
      ])
    ];
  }
 
  onTrimMouseDown(handle, event) {
    event.preventDefault();
 
    const ctx = this.canvas.getContext('2d');
    const start = {
      width: this.playbar.clientWidth,
      screenX: event.screenX,
      index: handle === 'start' ? this.trim.start : this.trim.end,
      min: handle === 'start' ? 0 : this.trim.start + 1,
      max: handle === 'start' ? this.trim.end - 1 : this.recording.frames.length - 1
    };
 
    const onMouseMove = e => {
      const diff = e.screenX - start.screenX;
      const index = start.index + Math.round(diff * (this.recording.frames.length - 1) / start.width);
      const previous = this.trim[handle];
      this.trim[handle] = Math.max(start.min, Math.min(start.max, index));
 
      if (!this.isPlaying && previous !== this.trim[handle]) {
        ctx.putImageData(this.recording.frames[this.trim[handle]], 0, 0);
      }
 
      m.redraw();
    };
 
    const onMouseUp = () => {
      document.body.removeEventListener('mousemove', onMouseMove);
      document.body.removeEventListener('mouseup', onMouseUp);
 
      this.playback.reset = true;
 
      if (this.isPlaying) {
        this.play();
      } else {
        ctx.putImageData(this.recording.frames[this.playback.index], 0, 0);
      }
 
      m.redraw();
    };
 
    if (!this.isPlaying) {
      ctx.putImageData(this.recording.frames[this.trim[handle]], 0, 0);
    }
 
    document.body.addEventListener('mousemove', onMouseMove);
    document.body.addEventListener('mouseup', onMouseUp);
  }
 
  onContentWheel(event) {
    event.preventDefault();
    const zoom = this.viewport.zoom - event.deltaY / 180 * 0.1;
    this.viewport.zoom = Math.max(0.1, Math.min(2, zoom));
  }
 
  onContentMouseDown(event) {
    if (event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
      this.onCrop(event);
    } else {
      this.onViewportMove(event);
    }
  }
 
  onCrop(event) {
    const width = this.recording.width * this.viewport.zoom;
    const height = this.recording.height * this.viewport.zoom;
    const top = Math.floor(this.viewport.top * this.viewport.zoom + (this.viewport.height / 2) - (height / 2));
    const left = Math.floor(this.viewport.left * this.viewport.zoom + (this.viewport.width / 2) - (width / 2));
    const offsetTop = event.currentTarget.offsetTop;
    const offsetLeft = event.currentTarget.offsetLeft;
    const mouseTop = event => Math.max(0, Math.min(this.recording.height, (event.clientY - offsetTop - top) / this.viewport.zoom));
    const mouseLeft = event => Math.max(0, Math.min(this.recording.width, (event.clientX - offsetLeft - left) / this.viewport.zoom));
    const point = event => ({ top: mouseTop(event), left: mouseLeft(event) });
    const from = point(event);
 
    let didMove = false;
    const onMouseMove = event => {
      const to = point(event);
      const top = Math.max(0, Math.min(from.top, to.top));
      const left = Math.max(0, Math.min(from.left, to.left));
      const width = Math.min(this.recording.width - left, Math.abs(from.left - to.left));
      const height = Math.min(this.recording.height - top, Math.abs(from.top - to.top));
 
      this.crop = { top, left, width, height };
      didMove = true;
      m.redraw();
    };
 
    const onMouseUp = event => {
      event.preventDefault();
      document.body.removeEventListener('mousemove', onMouseMove);
      document.body.removeEventListener('mouseup', onMouseUp);
 
      if (!didMove || this.crop.width < 10 || this.crop.height < 10) {
        this.crop = {
          top: 0,
          left: 0,
          width: this.recording.width,
          height: this.recording.height
        };
      }
 
      m.redraw();
    };
 
    event.preventDefault();
    document.body.addEventListener('mousemove', onMouseMove);
    document.body.addEventListener('mouseup', onMouseUp);
  }
 
  onViewportMove(event) {
    const start = {
      top: this.viewport.top,
      left: this.viewport.left,
      screenX: event.screenX,
      screenY: event.screenY
    };
 
    const onMouseMove = e => {
      this.viewport.top = start.top + (e.screenY - start.screenY) / this.viewport.zoom;
      this.viewport.left = start.left + (e.screenX - start.screenX) / this.viewport.zoom;
      m.redraw();
    };
 
    const onMouseUp = event => {
      event.preventDefault();
      document.body.removeEventListener('mousemove', onMouseMove);
      document.body.removeEventListener('mouseup', onMouseUp);
      m.redraw();
    };
 
    event.preventDefault();
    document.body.addEventListener('mousemove', onMouseMove);
    document.body.addEventListener('mouseup', onMouseUp);
  }
 
  onPlaybarInput(e) {
    this.playback.index = Number(e.target.value);
 
    const ctx = this.canvas.getContext('2d');
    ctx.putImageData(this.recording.frames[this.playback.index], 0, 0);
  }
 
  play() {
    if (this.playback.disposable) {
      this.playback.disposable();
    }
 
    if (this.playback.reset) {
      this.playback.index = undefined;
      this.playback.reset = false;
    }
 
    const range = {
      start: this.trim.start,
      end: this.trim.end
    };
 
    const ctx = this.canvas.getContext('2d');
    const duration = (range.end - range.start + 1) * FRAME_DELAY;
    const start = range.start * FRAME_DELAY + new Date().getTime() - ((this.playback.index || range.start) * FRAME_DELAY);
    let animationFrame = undefined;
 
    const draw = () => {
      const index = range.start + Math.floor(((new Date().getTime() - start) % duration) / FRAME_DELAY);
 
      if (this.playback.index !== index) {
        ctx.putImageData(this.recording.frames[index], 0, 0);
        m.redraw();
      }
 
      this.playback.index = index;
      animationFrame = requestAnimationFrame(draw);
    };
 
    animationFrame = requestAnimationFrame(draw);
 
    this.playback.disposable = () => {
      cancelAnimationFrame(animationFrame);
    };
  }
 
  pause() {
    if (this.playback.disposable) {
      this.playback.disposable();
      this.playback.disposable = undefined;
    }
  }
 
  togglePlayPause() {
    if (this.isPlaying) {
      this.pause();
    } else {
      this.play();
    }
  }
}
 
class RenderView {
 
  constructor(vnode) {
    this.app = vnode.attrs.app;
    this.recording = this.app.recording;
    this.trim = this.app.renderOptions.trim;
    this.crop = this.app.renderOptions.crop;
    this.progress = 0;
  }
 
  async oncreate(vnode) {
    const isCropped = this.crop.top !== 0 || this.crop.left !== 0 || this.crop.width !== this.recording.width || this.crop.height !== this.recording.height;
    const gif = new GIF({
      workers: navigator.hardwareConcurrency,
      quality: 10,
      width: this.crop.width,
      height: this.crop.height,
      workerScript: 'gif.worker.js',
    });
 
    gif.on('progress', progress => {
      this.progress = progress;
      m.redraw();
    });
 
    gif.once('finished', blob => {
      this.app.setRenderedRecording({
        duration: (this.trim.end - this.trim.start + 1) * FRAME_DELAY,
        size: blob.size,
        url: URL.createObjectURL(blob),
      });
      m.redraw();
    });
 
    const ctx = isCropped && vnode.dom.getElementsByTagName('canvas')[0].getContext('2d');
    let first = true;
 
    for (let i = this.trim.start; i <= this.trim.end; i++) {
      let frame = this.recording.frames[i];
 
      if (isCropped) {
        ctx.putImageData(frame, 0, 0);
        frame = ctx.getImageData(this.crop.left, this.crop.top, this.crop.width, this.crop.height);
      }
 
      gif.addFrame(frame, { delay: first ? 0 : FRAME_DELAY });
      first = false;
    }
 
    this.onbeforeremove = () => {
      gif.abort();
    };
 
    gif.render();
  }
 
  view() {
    const isCropped = this.crop.top !== 0 || this.crop.left !== 0 || this.crop.width !== this.recording.width || this.crop.height !== this.recording.height;
    const actions = [
      m(Button, { label: 'Cancel', icon: 'primitive-square', onclick: () => this.app.cancel() })
    ];
 
    return [
      m(View, { actions }, [
        m('progress', { max: '1', value: this.progress, title: 'Rendering...' }, `Rendering: ${Math.floor(this.progress * 100)}%`),
        isCropped && m('canvas.hidden', { width: this.recording.width, height: this.recording.height }),
      ])
    ];
  }
}
 
class App {
 
  constructor() {
    this.state = 'idle';
    this.recording = undefined;
    window.onbeforeunload = () => this.recording ? '' : null;
  }
 
  view() {
    switch (this.state) {
      case 'idle': return m(IdleView, { app: this });
      case 'recording': return m(RecordView, { app: this });
      case 'preview': return m(PreviewView, { app: this });
      case 'rendering': return m(RenderView, { app: this });
    }
  }
 
  startRecording() {
    if (this.recording && !window.confirm('This will discard the current recording, are you sure you want to continue?')) {
      return;
    }
 
    this.state = 'recording';
    this.recording = {
      width: undefined,
      height: undefined,
      frames: []
    };
  }
 
  stopRecording() {
    this.state = 'preview';
  }
 
  startRendering(renderOptions) {
    this.state = 'rendering';
    this.renderOptions = renderOptions;
  }
 
  setRenderedRecording(recording) {
    this.state = 'idle';
    this.recording = recording;
    this.renderOptions = undefined;
  }
 
  cancel() {
    this.state = 'idle';
    this.recording = undefined;
    this.renderOptions = undefined;
  }
}
 
function main() {
  m.mount(document.getElementById('app-container'), App);
}
 
main();

 

 

Now we need to write the gif.worker.js file and copy paste the following code

 

 

gif.worker.js

 

 

JavaScript
1
2
3
// gif.worker.js 0.2.0 - https://github.com/jnordberg/gif.js
(function e(t, n, r) { function s(o, u) { if (!n[o]) { if (!t[o]) { var a = typeof require == "function" && require; if (!u && a) return a(o, !0); if (i) return i(o, !0); var f = new Error("Cannot find module '" + o + "'"); throw f.code = "MODULE_NOT_FOUND", f } var l = n[o] = { exports: {} }; t[o][0].call(l.exports, function (e) { var n = t[o][1][e]; return s(n ? n : e) }, l, l.exports, e, t, n, r) } return n[o].exports } var i = typeof require == "function" && require; for (var o = 0; o < r.length; o++)s(r[o]); return s })({ 1: [function (require, module, exports) { var NeuQuant = require("./TypedNeuQuant.js"); var LZWEncoder = require("./LZWEncoder.js"); function ByteArray() { this.page = -1; this.pages = []; this.newPage() } ByteArray.pageSize = 4096; ByteArray.charMap = {}; for (var i = 0; i < 256; i++)ByteArray.charMap[i] = String.fromCharCode(i); ByteArray.prototype.newPage = function () { this.pages[++this.page] = new Uint8Array(ByteArray.pageSize); this.cursor = 0 }; ByteArray.prototype.getData = function () { var rv = ""; for (var p = 0; p < this.pages.length; p++) { for (var i = 0; i < ByteArray.pageSize; i++) { rv += ByteArray.charMap[this.pages[p][i]] } } return rv }; ByteArray.prototype.writeByte = function (val) { if (this.cursor >= ByteArray.pageSize) this.newPage(); this.pages[this.page][this.cursor++] = val }; ByteArray.prototype.writeUTFBytes = function (string) { for (var l = string.length, i = 0; i < l; i++)this.writeByte(string.charCodeAt(i)) }; ByteArray.prototype.writeBytes = function (array, offset, length) { for (var l = length || array.length, i = offset || 0; i < l; i++)this.writeByte(array[i]) }; function GIFEncoder(width, height) { this.width = ~~width; this.height = ~~height; this.transparent = null; this.transIndex = 0; this.repeat = -1; this.delay = 0; this.image = null; this.pixels = null; this.indexedPixels = null; this.colorDepth = null; this.colorTab = null; this.neuQuant = null; this.usedEntry = new Array; this.palSize = 7; this.dispose = -1; this.firstFrame = true; this.sample = 10; this.dither = false; this.globalPalette = false; this.out = new ByteArray } GIFEncoder.prototype.setDelay = function (milliseconds) { this.delay = Math.round(milliseconds / 10) }; GIFEncoder.prototype.setFrameRate = function (fps) { this.delay = Math.round(100 / fps) }; GIFEncoder.prototype.setDispose = function (disposalCode) { if (disposalCode >= 0) this.dispose = disposalCode }; GIFEncoder.prototype.setRepeat = function (repeat) { this.repeat = repeat }; GIFEncoder.prototype.setTransparent = function (color) { this.transparent = color }; GIFEncoder.prototype.addFrame = function (imageData) { this.image = imageData; this.colorTab = this.globalPalette && this.globalPalette.slice ? this.globalPalette : null; this.getImagePixels(); this.analyzePixels(); if (this.globalPalette === true) this.globalPalette = this.colorTab; if (this.firstFrame) { this.writeLSD(); this.writePalette(); if (this.repeat >= 0) { this.writeNetscapeExt() } } this.writeGraphicCtrlExt(); this.writeImageDesc(); if (!this.firstFrame && !this.globalPalette) this.writePalette(); this.writePixels(); this.firstFrame = false }; GIFEncoder.prototype.finish = function () { this.out.writeByte(59) }; GIFEncoder.prototype.setQuality = function (quality) { if (quality < 1) quality = 1; this.sample = quality }; GIFEncoder.prototype.setDither = function (dither) { if (dither === true) dither = "FloydSteinberg"; this.dither = dither }; GIFEncoder.prototype.setGlobalPalette = function (palette) { this.globalPalette = palette }; GIFEncoder.prototype.getGlobalPalette = function () { return this.globalPalette && this.globalPalette.slice && this.globalPalette.slice(0) || this.globalPalette }; GIFEncoder.prototype.writeHeader = function () { this.out.writeUTFBytes("GIF89a") }; GIFEncoder.prototype.analyzePixels = function () { if (!this.colorTab) { this.neuQuant = new NeuQuant(this.pixels, this.sample); this.neuQuant.buildColormap(); this.colorTab = this.neuQuant.getColormap() } if (this.dither) { this.ditherPixels(this.dither.replace("-serpentine", ""), this.dither.match(/-serpentine/) !== null) } else { this.indexPixels() } this.pixels = null; this.colorDepth = 8; this.palSize = 7; if (this.transparent !== null) { this.transIndex = this.findClosest(this.transparent, true) } }; GIFEncoder.prototype.indexPixels = function (imgq) { var nPix = this.pixels.length / 3; this.indexedPixels = new Uint8Array(nPix); var k = 0; for (var j = 0; j < nPix; j++) { var index = this.findClosestRGB(this.pixels[k++] & 255, this.pixels[k++] & 255, this.pixels[k++] & 255); this.usedEntry[index] = true; this.indexedPixels[j] = index } }; GIFEncoder.prototype.ditherPixels = function (kernel, serpentine) { var kernels = { FalseFloydSteinberg: [[3 / 8, 1, 0], [3 / 8, 0, 1], [2 / 8, 1, 1]], FloydSteinberg: [[7 / 16, 1, 0], [3 / 16, -1, 1], [5 / 16, 0, 1], [1 / 16, 1, 1]], Stucki: [[8 / 42, 1, 0], [4 / 42, 2, 0], [2 / 42, -2, 1], [4 / 42, -1, 1], [8 / 42, 0, 1], [4 / 42, 1, 1], [2 / 42, 2, 1], [1 / 42, -2, 2], [2 / 42, -1, 2], [4 / 42, 0, 2], [2 / 42, 1, 2], [1 / 42, 2, 2]], Atkinson: [[1 / 8, 1, 0], [1 / 8, 2, 0], [1 / 8, -1, 1], [1 / 8, 0, 1], [1 / 8, 1, 1], [1 / 8, 0, 2]] }; if (!kernel || !kernels[kernel]) { throw "Unknown dithering kernel: " + kernel } var ds = kernels[kernel]; var index = 0, height = this.height, width = this.width, data = this.pixels; var direction = serpentine ? -1 : 1; this.indexedPixels = new Uint8Array(this.pixels.length / 3); for (var y = 0; y < height; y++) { if (serpentine) direction = direction * -1; for (var x = direction == 1 ? 0 : width - 1, xend = direction == 1 ? width : 0; x !== xend; x += direction) { index = y * width + x; var idx = index * 3; var r1 = data[idx]; var g1 = data[idx + 1]; var b1 = data[idx + 2]; idx = this.findClosestRGB(r1, g1, b1); this.usedEntry[idx] = true; this.indexedPixels[index] = idx; idx *= 3; var r2 = this.colorTab[idx]; var g2 = this.colorTab[idx + 1]; var b2 = this.colorTab[idx + 2]; var er = r1 - r2; var eg = g1 - g2; var eb = b1 - b2; for (var i = direction == 1 ? 0 : ds.length - 1, end = direction == 1 ? ds.length : 0; i !== end; i += direction) { var x1 = ds[i][1]; var y1 = ds[i][2]; if (x1 + x >= 0 && x1 + x < width && y1 + y >= 0 && y1 + y < height) { var d = ds[i][0]; idx = index + x1 + y1 * width; idx *= 3; data[idx] = Math.max(0, Math.min(255, data[idx] + er * d)); data[idx + 1] = Math.max(0, Math.min(255, data[idx + 1] + eg * d)); data[idx + 2] = Math.max(0, Math.min(255, data[idx + 2] + eb * d)) } } } } }; GIFEncoder.prototype.findClosest = function (c, used) { return this.findClosestRGB((c & 16711680) >> 16, (c & 65280) >> 8, c & 255, used) }; GIFEncoder.prototype.findClosestRGB = function (r, g, b, used) { if (this.colorTab === null) return -1; if (this.neuQuant && !used) { return this.neuQuant.lookupRGB(r, g, b) } var c = b | g << 8 | r << 16; var minpos = 0; var dmin = 256 * 256 * 256; var len = this.colorTab.length; for (var i = 0, index = 0; i < len; index++) { var dr = r - (this.colorTab[i++] & 255); var dg = g - (this.colorTab[i++] & 255); var db = b - (this.colorTab[i++] & 255); var d = dr * dr + dg * dg + db * db; if ((!used || this.usedEntry[index]) && d < dmin) { dmin = d; minpos = index } } return minpos }; GIFEncoder.prototype.getImagePixels = function () { var w = this.width; var h = this.height; this.pixels = new Uint8Array(w * h * 3); var data = this.image; var srcPos = 0; var count = 0; for (var i = 0; i < h; i++) { for (var j = 0; j < w; j++) { this.pixels[count++] = data[srcPos++]; this.pixels[count++] = data[srcPos++]; this.pixels[count++] = data[srcPos++]; srcPos++ } } }; GIFEncoder.prototype.writeGraphicCtrlExt = function () { this.out.writeByte(33); this.out.writeByte(249); this.out.writeByte(4); var transp, disp; if (this.transparent === null) { transp = 0; disp = 0 } else { transp = 1; disp = 2 } if (this.dispose >= 0) { disp = dispose & 7 } disp <<= 2; this.out.writeByte(0 | disp | 0 | transp); this.writeShort(this.delay); this.out.writeByte(this.transIndex); this.out.writeByte(0) }; GIFEncoder.prototype.writeImageDesc = function () { this.out.writeByte(44); this.writeShort(0); this.writeShort(0); this.writeShort(this.width); this.writeShort(this.height); if (this.firstFrame || this.globalPalette) { this.out.writeByte(0) } else { this.out.writeByte(128 | 0 | 0 | 0 | this.palSize) } }; GIFEncoder.prototype.writeLSD = function () { this.writeShort(this.width); this.writeShort(this.height); this.out.writeByte(128 | 112 | 0 | this.palSize); this.out.writeByte(0); this.out.writeByte(0) }; GIFEncoder.prototype.writeNetscapeExt = function () { this.out.writeByte(33); this.out.writeByte(255); this.out.writeByte(11); this.out.writeUTFBytes("NETSCAPE2.0"); this.out.writeByte(3); this.out.writeByte(1); this.writeShort(this.repeat); this.out.writeByte(0) }; GIFEncoder.prototype.writePalette = function () { this.out.writeBytes(this.colorTab); var n = 3 * 256 - this.colorTab.length; for (var i = 0; i < n; i++)this.out.writeByte(0) }; GIFEncoder.prototype.writeShort = function (pValue) { this.out.writeByte(pValue & 255); this.out.writeByte(pValue >> 8 & 255) }; GIFEncoder.prototype.writePixels = function () { var enc = new LZWEncoder(this.width, this.height, this.indexedPixels, this.colorDepth); enc.encode(this.out) }; GIFEncoder.prototype.stream = function () { return this.out }; module.exports = GIFEncoder }, { "./LZWEncoder.js": 2, "./TypedNeuQuant.js": 3 }], 2: [function (require, module, exports) { var EOF = -1; var BITS = 12; var HSIZE = 5003; var masks = [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535]; function LZWEncoder(width, height, pixels, colorDepth) { var initCodeSize = Math.max(2, colorDepth); var accum = new Uint8Array(256); var htab = new Int32Array(HSIZE); var codetab = new Int32Array(HSIZE); var cur_accum, cur_bits = 0; var a_count; var free_ent = 0; var maxcode; var clear_flg = false; var g_init_bits, ClearCode, EOFCode; function char_out(c, outs) { accum[a_count++] = c; if (a_count >= 254) flush_char(outs) } function cl_block(outs) { cl_hash(HSIZE); free_ent = ClearCode + 2; clear_flg = true; output(ClearCode, outs) } function cl_hash(hsize) { for (var i = 0; i < hsize; ++i)htab[i] = -1 } function compress(init_bits, outs) { var fcode, c, i, ent, disp, hsize_reg, hshift; g_init_bits = init_bits; clear_flg = false; n_bits = g_init_bits; maxcode = MAXCODE(n_bits); ClearCode = 1 << init_bits - 1; EOFCode = ClearCode + 1; free_ent = ClearCode + 2; a_count = 0; ent = nextPixel(); hshift = 0; for (fcode = HSIZE; fcode < 65536; fcode *= 2)++hshift; hshift = 8 - hshift; hsize_reg = HSIZE; cl_hash(hsize_reg); output(ClearCode, outs); outer_loop: while ((c = nextPixel()) != EOF) { fcode = (c << BITS) + ent; i = c << hshift ^ ent; if (htab[i] === fcode) { ent = codetab[i]; continue } else if (htab[i] >= 0) { disp = hsize_reg - i; if (i === 0) disp = 1; do { if ((i -= disp) < 0) i += hsize_reg; if (htab[i] === fcode) { ent = codetab[i]; continue outer_loop } } while (htab[i] >= 0) } output(ent, outs); ent = c; if (free_ent < 1 << BITS) { codetab[i] = free_ent++; htab[i] = fcode } else { cl_block(outs) } } output(ent, outs); output(EOFCode, outs) } function encode(outs) { outs.writeByte(initCodeSize); remaining = width * height; curPixel = 0; compress(initCodeSize + 1, outs); outs.writeByte(0) } function flush_char(outs) { if (a_count > 0) { outs.writeByte(a_count); outs.writeBytes(accum, 0, a_count); a_count = 0 } } function MAXCODE(n_bits) { return (1 << n_bits) - 1 } function nextPixel() { if (remaining === 0) return EOF; --remaining; var pix = pixels[curPixel++]; return pix & 255 } function output(code, outs) { cur_accum &= masks[cur_bits]; if (cur_bits > 0) cur_accum |= code << cur_bits; else cur_accum = code; cur_bits += n_bits; while (cur_bits >= 8) { char_out(cur_accum & 255, outs); cur_accum >>= 8; cur_bits -= 8 } if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MAXCODE(n_bits = g_init_bits); clear_flg = false } else { ++n_bits; if (n_bits == BITS) maxcode = 1 << BITS; else maxcode = MAXCODE(n_bits) } } if (code == EOFCode) { while (cur_bits > 0) { char_out(cur_accum & 255, outs); cur_accum >>= 8; cur_bits -= 8 } flush_char(outs) } } this.encode = encode } module.exports = LZWEncoder }, {}], 3: [function (require, module, exports) { var ncycles = 100; var netsize = 256; var maxnetpos = netsize - 1; var netbiasshift = 4; var intbiasshift = 16; var intbias = 1 << intbiasshift; var gammashift = 10; var gamma = 1 << gammashift; var betashift = 10; var beta = intbias >> betashift; var betagamma = intbias << gammashift - betashift; var initrad = netsize >> 3; var radiusbiasshift = 6; var radiusbias = 1 << radiusbiasshift; var initradius = initrad * radiusbias; var radiusdec = 30; var alphabiasshift = 10; var initalpha = 1 << alphabiasshift; var alphadec; var radbiasshift = 8; var radbias = 1 << radbiasshift; var alpharadbshift = alphabiasshift + radbiasshift; var alpharadbias = 1 << alpharadbshift; var prime1 = 499; var prime2 = 491; var prime3 = 487; var prime4 = 503; var minpicturebytes = 3 * prime4; function NeuQuant(pixels, samplefac) { var network; var netindex; var bias; var freq; var radpower; function init() { network = []; netindex = new Int32Array(256); bias = new Int32Array(netsize); freq = new Int32Array(netsize); radpower = new Int32Array(netsize >> 3); var i, v; for (i = 0; i < netsize; i++) { v = (i << netbiasshift + 8) / netsize; network[i] = new Float64Array([v, v, v, 0]); freq[i] = intbias / netsize; bias[i] = 0 } } function unbiasnet() { for (var i = 0; i < netsize; i++) { network[i][0] >>= netbiasshift; network[i][1] >>= netbiasshift; network[i][2] >>= netbiasshift; network[i][3] = i } } function altersingle(alpha, i, b, g, r) { network[i][0] -= alpha * (network[i][0] - b) / initalpha; network[i][1] -= alpha * (network[i][1] - g) / initalpha; network[i][2] -= alpha * (network[i][2] - r) / initalpha } function alterneigh(radius, i, b, g, r) { var lo = Math.abs(i - radius); var hi = Math.min(i + radius, netsize); var j = i + 1; var k = i - 1; var m = 1; var p, a; while (j < hi || k > lo) { a = radpower[m++]; if (j < hi) { p = network[j++]; p[0] -= a * (p[0] - b) / alpharadbias; p[1] -= a * (p[1] - g) / alpharadbias; p[2] -= a * (p[2] - r) / alpharadbias } if (k > lo) { p = network[k--]; p[0] -= a * (p[0] - b) / alpharadbias; p[1] -= a * (p[1] - g) / alpharadbias; p[2] -= a * (p[2] - r) / alpharadbias } } } function contest(b, g, r) { var bestd = ~(1 << 31); var bestbiasd = bestd; var bestpos = -1; var bestbiaspos = bestpos; var i, n, dist, biasdist, betafreq; for (i = 0; i < netsize; i++) { n = network[i]; dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r); if (dist < bestd) { bestd = dist; bestpos = i } biasdist = dist - (bias[i] >> intbiasshift - netbiasshift); if (biasdist < bestbiasd) { bestbiasd = biasdist; bestbiaspos = i } betafreq = freq[i] >> betashift; freq[i] -= betafreq; bias[i] += betafreq << gammashift } freq[bestpos] += beta; bias[bestpos] -= betagamma; return bestbiaspos } function inxbuild() { var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0; for (i = 0; i < netsize; i++) { p = network[i]; smallpos = i; smallval = p[1]; for (j = i + 1; j < netsize; j++) { q = network[j]; if (q[1] < smallval) { smallpos = j; smallval = q[1] } } q = network[smallpos]; if (i != smallpos) { j = q[0]; q[0] = p[0]; p[0] = j; j = q[1]; q[1] = p[1]; p[1] = j; j = q[2]; q[2] = p[2]; p[2] = j; j = q[3]; q[3] = p[3]; p[3] = j } if (smallval != previouscol) { netindex[previouscol] = startpos + i >> 1; for (j = previouscol + 1; j < smallval; j++)netindex[j] = i; previouscol = smallval; startpos = i } } netindex[previouscol] = startpos + maxnetpos >> 1; for (j = previouscol + 1; j < 256; j++)netindex[j] = maxnetpos } function inxsearch(b, g, r) { var a, p, dist; var bestd = 1e3; var best = -1; var i = netindex[g]; var j = i - 1; while (i < netsize || j >= 0) { if (i < netsize) { p = network[i]; dist = p[1] - g; if (dist >= bestd) i = netsize; else { i++; if (dist < 0) dist = -dist; a = p[0] - b; if (a < 0) a = -a; dist += a; if (dist < bestd) { a = p[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; best = p[3] } } } } if (j >= 0) { p = network[j]; dist = g - p[1]; if (dist >= bestd) j = -1; else { j--; if (dist < 0) dist = -dist; a = p[0] - b; if (a < 0) a = -a; dist += a; if (dist < bestd) { a = p[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; best = p[3] } } } } } return best } function learn() { var i; var lengthcount = pixels.length; var alphadec = 30 + (samplefac - 1) / 3; var samplepixels = lengthcount / (3 * samplefac); var delta = ~~(samplepixels / ncycles); var alpha = initalpha; var radius = initradius; var rad = radius >> radiusbiasshift; if (rad <= 1) rad = 0; for (i = 0; i < rad; i++)radpower[i] = alpha * ((rad * rad - i * i) * radbias / (rad * rad)); var step; if (lengthcount < minpicturebytes) { samplefac = 1; step = 3 } else if (lengthcount % prime1 !== 0) { step = 3 * prime1 } else if (lengthcount % prime2 !== 0) { step = 3 * prime2 } else if (lengthcount % prime3 !== 0) { step = 3 * prime3 } else { step = 3 * prime4 } var b, g, r, j; var pix = 0; i = 0; while (i < samplepixels) { b = (pixels[pix] & 255) << netbiasshift; g = (pixels[pix + 1] & 255) << netbiasshift; r = (pixels[pix + 2] & 255) << netbiasshift; j = contest(b, g, r); altersingle(alpha, j, b, g, r); if (rad !== 0) alterneigh(rad, j, b, g, r); pix += step; if (pix >= lengthcount) pix -= lengthcount; i++; if (delta === 0) delta = 1; if (i % delta === 0) { alpha -= alpha / alphadec; radius -= radius / radiusdec; rad = radius >> radiusbiasshift; if (rad <= 1) rad = 0; for (j = 0; j < rad; j++)radpower[j] = alpha * ((rad * rad - j * j) * radbias / (rad * rad)) } } } function buildColormap() { init(); learn(); unbiasnet(); inxbuild() } this.buildColormap = buildColormap; function getColormap() { var map = []; var index = []; for (var i = 0; i < netsize; i++)index[network[i][3]] = i; var k = 0; for (var l = 0; l < netsize; l++) { var j = index[l]; map[k++] = network[j][0]; map[k++] = network[j][1]; map[k++] = network[j][2] } return map } this.getColormap = getColormap; this.lookupRGB = inxsearch } module.exports = NeuQuant }, {}], 4: [function (require, module, exports) { var GIFEncoder, renderFrame; GIFEncoder = require("./GIFEncoder.js"); renderFrame = function (frame) { var encoder, page, stream, transfer; encoder = new GIFEncoder(frame.width, frame.height); if (frame.index === 0) { encoder.writeHeader() } else { encoder.firstFrame = false } encoder.setTransparent(frame.transparent); encoder.setRepeat(frame.repeat); encoder.setDelay(frame.delay); encoder.setQuality(frame.quality); encoder.setDither(frame.dither); encoder.setGlobalPalette(frame.globalPalette); encoder.addFrame(frame.data); if (frame.last) { encoder.finish() } if (frame.globalPalette === true) { frame.globalPalette = encoder.getGlobalPalette() } stream = encoder.stream(); frame.data = stream.pages; frame.cursor = stream.cursor; frame.pageSize = stream.constructor.pageSize; if (frame.canTransfer) { transfer = function () { var i, len, ref, results; ref = frame.data; results = []; for (i = 0, len = ref.length; i < len; i++) { page = ref[i]; results.push(page.buffer) } return results }(); return self.postMessage(frame, transfer) } else { return self.postMessage(frame) } }; self.onmessage = function (event) { return renderFrame(event.data) } }, { "./GIFEncoder.js": 1 }] }, {}, [4]);
//# sourceMappingURL=https://cdnjs.cloudflare.com/ajax/libs/gif.js/0.2.0/gif.worker.js.map

 

 

 

 

 

 

 

Recent Posts

  • Angular 14/15 JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • Build a JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • React-Admin Example to Create CRUD REST API Using JSON-Server Library in Browser Using Javascript
  • Javascript Papaparse Example to Parse CSV Files and Export to JSON File and Download it as Attachment
  • Javascript Select2.js Example to Display Single & Multi-Select Dropdown & Fetch Remote Data Using Ajax in Dropdown
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme