-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
loading_displaying.js
1504 lines (1402 loc) · 41.7 KB
/
loading_displaying.js
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module Image
* @submodule Loading & Displaying
* @for p5
* @requires core
*/
import p5 from '../core/main';
import canvas from '../core/helpers';
import * as constants from '../core/constants';
import omggif from 'omggif';
import { GIFEncoder, quantize, nearestColorIndex } from 'gifenc';
import '../core/friendly_errors/validate_params';
import '../core/friendly_errors/file_errors';
import '../core/friendly_errors/fes_core';
/**
* Loads an image to create a <a href="#/p5.Image">p5.Image</a> object.
*
* `loadImage()` interprets the first parameter one of three ways. If the path
* to an image file is provided, `loadImage()` will load it. Paths to local
* files should be relative, such as `'assets/thundercat.jpg'`. URLs such as
* `'https://example.com/thundercat.jpg'` may be blocked due to browser
* security. Raw image data can also be passed as a base64 encoded image in
* the form `'data:image/png;base64,arandomsequenceofcharacters'`.
*
* The second parameter is optional. If a function is passed, it will be
* called once the image has loaded. The callback function can optionally use
* the new <a href="#/p5.Image">p5.Image</a> object.
*
* The third parameter is also optional. If a function is passed, it will be
* called if the image fails to load. The callback function can optionally use
* the event error.
*
* Images can take time to load. Calling `loadImage()` in
* <a href="#/p5/preload">preload()</a> ensures images load before they're
* used in <a href="#/p5/setup">setup()</a> or <a href="#/p5/draw">draw()</a>.
*
* @method loadImage
* @param {String} path path of the image to be loaded or base64 encoded image.
* @param {function(p5.Image)} [successCallback] function called with
* <a href="#/p5.Image">p5.Image</a> once it
* loads.
* @param {function(Event)} [failureCallback] function called with event
* error if the image fails to load.
* @return {p5.Image} the <a href="#/p5.Image">p5.Image</a> object.
*
* @example
* <div>
* <code>
* let img;
*
* // Load the image and create a p5.Image object.
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* // Draw the image.
* image(img, 0, 0);
*
* describe('Image of the underside of a white umbrella and a gridded ceiling.');
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* // Call handleImage() once the image loads.
* loadImage('assets/laDefense.jpg', handleImage);
*
* describe('Image of the underside of a white umbrella and a gridded ceiling.');
* }
*
* // Display the image.
* function handleImage(img) {
* image(img, 0, 0);
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* // Call handleImage() once the image loads or
* // call handleError() if an error occurs.
* loadImage('assets/laDefense.jpg', handleImage, handleError);
* }
*
* // Display the image.
* function handleImage(img) {
* image(img, 0, 0);
*
* describe('Image of the underside of a white umbrella and a gridded ceiling.');
* }
*
* // Log the error.
* function handleError(event) {
* console.error('Oops!', event);
* }
* </code>
* </div>
*/
p5.prototype.loadImage = function(path, successCallback, failureCallback) {
p5._validateParameters('loadImage', arguments);
const pImg = new p5.Image(1, 1, this);
const self = this;
const req = new Request(path, {
method: 'GET',
mode: 'cors'
});
fetch(path, req)
.then(response => {
// GIF section
const contentType = response.headers.get('content-type');
if (contentType === null) {
console.warn(
'The image you loaded does not have a Content-Type header. If you are using the online editor consider reuploading the asset.'
);
}
if (contentType && contentType.includes('image/gif')) {
response.arrayBuffer().then(
arrayBuffer => {
if (arrayBuffer) {
const byteArray = new Uint8Array(arrayBuffer);
_createGif(
byteArray,
pImg,
successCallback,
failureCallback,
(pImg => {
self._decrementPreload();
}).bind(self)
);
}
},
e => {
if (typeof failureCallback === 'function') {
failureCallback(e);
self._decrementPreload();
} else {
console.error(e);
}
}
);
} else {
// Non-GIF Section
const img = new Image();
img.onload = () => {
pImg.width = pImg.canvas.width = img.width;
pImg.height = pImg.canvas.height = img.height;
// Draw the image into the backing canvas of the p5.Image
pImg.drawingContext.drawImage(img, 0, 0);
pImg.modified = true;
if (typeof successCallback === 'function') {
successCallback(pImg);
}
self._decrementPreload();
};
img.onerror = e => {
p5._friendlyFileLoadError(0, img.src);
if (typeof failureCallback === 'function') {
failureCallback(e);
self._decrementPreload();
} else {
console.error(e);
}
};
// Set crossOrigin in case image is served with CORS headers.
// This will let us draw to the canvas without tainting it.
// See https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image
// When using data-uris the file will be loaded locally
// so we don't need to worry about crossOrigin with base64 file types.
if (path.indexOf('data:image/') !== 0) {
img.crossOrigin = 'Anonymous';
}
// start loading the image
img.src = path;
}
pImg.modified = true;
})
.catch(e => {
p5._friendlyFileLoadError(0, path);
if (typeof failureCallback === 'function') {
failureCallback(e);
self._decrementPreload();
} else {
console.error(e);
}
});
return pImg;
};
/**
* Generates a gif from a sketch and saves it to a file.
*
* `saveGif()` may be called in <a href="#/p5/setup">setup()</a> or at any
* point while a sketch is running.
*
* The first parameter, `fileName`, sets the gif's file name.
*
* The second parameter, `duration`, sets the gif's duration in seconds.
*
* The third parameter, `options`, is optional. If an object is passed,
* `saveGif()` will use its properties to customize the gif. `saveGif()`
* recognizes the properties `delay`, `units`, `silent`,
* `notificationDuration`, and `notificationID`.
*
* @method saveGif
* @param {String} filename file name of gif.
* @param {Number} duration duration in seconds to capture from the sketch.
* @param {Object} [options] an object that can contain five more properties:
* `delay`, a Number specifying how much time to wait before recording;
* `units`, a String that can be either 'seconds' or 'frames'. By default it's 'seconds’;
* `silent`, a Boolean that defines presence of progress notifications. By default it’s `false`;
* `notificationDuration`, a Number that defines how long in seconds the final notification
* will live. By default it's `0`, meaning the notification will never be removed;
* `notificationID`, a String that specifies the id of the notification's DOM element. By default it’s `'progressBar’`.
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.');
* }
*
* function draw() {
* background(200);
*
* // Style the circle.
* let c = frameCount % 255;
* fill(c);
*
* // Display the circle.
* circle(50, 50, 25);
* }
*
* // Save a 5-second gif when the user presses the 's' key.
* function keyPressed() {
* if (key === 's') {
* saveGif('mySketch', 5);
* }
* }
* </code>
* </div>
*
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.');
* }
*
* function draw() {
* background(200);
*
* // Style the circle.
* let c = frameCount % 255;
* fill(c);
*
* // Display the circle.
* circle(50, 50, 25);
* }
*
* // Save a 5-second gif when the user presses the 's' key.
* // Wait 1 second after the key press before recording.
* function keyPressed() {
* if (key === 's') {
* saveGif('mySketch', 5, { delay: 1 });
* }
* }
* </code>
* </div>
*/
p5.prototype.saveGif = async function(
fileName,
duration,
options = {
delay: 0,
units: 'seconds',
silent: false,
notificationDuration: 0,
notificationID: 'progressBar'
}
) {
// validate parameters
if (typeof fileName !== 'string') {
throw TypeError('fileName parameter must be a string');
}
if (typeof duration !== 'number') {
throw TypeError('Duration parameter must be a number');
}
// extract variables for more comfortable use
const delay = (options && options.delay) || 0; // in seconds
const units = (options && options.units) || 'seconds'; // either 'seconds' or 'frames'
const silent = (options && options.silent) || false;
const notificationDuration = (options && options.notificationDuration) || 0;
const notificationID = (options && options.notificationID) || 'progressBar';
// if arguments in the options object are not correct, cancel operation
if (typeof delay !== 'number') {
throw TypeError('Delay parameter must be a number');
}
// if units is not seconds nor frames, throw error
if (units !== 'seconds' && units !== 'frames') {
throw TypeError('Units parameter must be either "frames" or "seconds"');
}
if (typeof silent !== 'boolean') {
throw TypeError('Silent parameter must be a boolean');
}
if (typeof notificationDuration !== 'number') {
throw TypeError('Notification duration parameter must be a number');
}
if (typeof notificationID !== 'string') {
throw TypeError('Notification ID parameter must be a string');
}
this._recording = true;
// get the project's framerate
let _frameRate = this._targetFrameRate;
// if it is undefined or some non useful value, assume it's 60
if (_frameRate === Infinity || _frameRate === undefined || _frameRate === 0) {
_frameRate = 60;
}
// calculate frame delay based on frameRate
// this delay has nothing to do with the
// delay in options, but rather is the delay
// we have to specify to the gif encoder between frames.
let gifFrameDelay = 1 / _frameRate * 1000;
// constrain it to be always greater than 20,
// otherwise it won't work in some browsers and systems
// reference: https://stackoverflow.com/questions/64473278/gif-frame-duration-seems-slower-than-expected
gifFrameDelay = gifFrameDelay < 20 ? 20 : gifFrameDelay;
// check the mode we are in and how many frames
// that duration translates to
const nFrames = units === 'seconds' ? duration * _frameRate : duration;
const nFramesDelay = units === 'seconds' ? delay * _frameRate : delay;
const totalNumberOfFrames = nFrames + nFramesDelay;
// initialize variables for the frames processing
let frameIterator = nFramesDelay;
this.frameCount = frameIterator;
const lastPixelDensity = this._pixelDensity;
this.pixelDensity(1);
// We first take every frame that we are going to use for the animation
let frames = [];
if (document.getElementById(notificationID) !== null)
document.getElementById(notificationID).remove();
let p;
if (!silent){
p = this.createP('');
p.id(notificationID);
p.style('font-size', '16px');
p.style('font-family', 'Montserrat');
p.style('background-color', '#ffffffa0');
p.style('padding', '8px');
p.style('border-radius', '10px');
p.position(0, 0);
}
let pixels;
let gl;
if (this._renderer instanceof p5.RendererGL) {
// if we have a WEBGL context, initialize the pixels array
// and the gl context to use them inside the loop
gl = this.drawingContext;
pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
}
// stop the loop since we are going to manually redraw
this.noLoop();
// Defer execution until the rest of the call stack finishes, allowing the
// rest of `setup` to be called (and, importantly, canvases hidden in setup
// to be unhidden.)
//
// Waiting on this empty promise means we'll continue as soon as setup
// finishes without waiting for another frame.
await Promise.resolve();
while (frameIterator < totalNumberOfFrames) {
/*
we draw the next frame. this is important, since
busy sketches or low end devices might take longer
to render some frames. So we just wait for the frame
to be drawn and immediately save it to a buffer and continue
*/
this.redraw();
// depending on the context we'll extract the pixels one way
// or another
let data = undefined;
if (this._renderer instanceof p5.RendererGL) {
pixels = new Uint8Array(
gl.drawingBufferWidth * gl.drawingBufferHeight * 4
);
gl.readPixels(
0,
0,
gl.drawingBufferWidth,
gl.drawingBufferHeight,
gl.RGBA,
gl.UNSIGNED_BYTE,
pixels
);
data = _flipPixels(pixels, this.width, this.height);
} else {
data = this.drawingContext.getImageData(0, 0, this.width, this.height)
.data;
}
frames.push(data);
frameIterator++;
if (!silent) {
p.html(
'Saved frame <b>' +
frames.length.toString() +
'</b> out of ' +
nFrames.toString()
);
}
await new Promise(resolve => setTimeout(resolve, 0));
}
if (!silent) p.html('Frames processed, generating color palette...');
this.loop();
this.pixelDensity(lastPixelDensity);
// create the gif encoder and the colorspace format
const gif = GIFEncoder();
// calculate the global palette for this set of frames
const globalPalette = _generateGlobalPalette(frames);
// Rather than using applyPalette() from the gifenc library, we use our
// own function to map frame pixels to a palette color. This way, we can
// cache palette color mappings between frames for extra performance, and
// use our own caching mechanism to avoid flickering colors from cache
// key collisions.
const paletteCache = {};
const getIndexedFrame = frame => {
const length = frame.length / 4;
const index = new Uint8Array(length);
for (let i = 0; i < length; i++) {
const key =
(frame[i * 4] << 24) |
(frame[i * 4 + 1] << 16) |
(frame[i * 4 + 2] << 8) |
frame[i * 4 + 3];
if (paletteCache[key] === undefined) {
paletteCache[key] = nearestColorIndex(
globalPalette,
frame.slice(i * 4, (i + 1) * 4)
);
}
index[i] = paletteCache[key];
}
return index;
};
// the way we designed the palette means we always take the last index for transparency
const transparentIndex = globalPalette.length - 1;
// we are going to iterate the frames in pairs, n-1 and n
let prevIndexedFrame = [];
for (let i = 0; i < frames.length; i++) {
//const indexedFrame = applyPalette(frames[i], globalPaletteWithoutAlpha, 'rgba565');
const indexedFrame = getIndexedFrame(frames[i]);
// Make a copy of the palette-applied frame before editing the original
// to use transparent pixels
const originalIndexedFrame = indexedFrame.slice();
if (i === 0) {
gif.writeFrame(indexedFrame, this.width, this.height, {
palette: globalPalette,
delay: gifFrameDelay,
dispose: 1
});
} else {
// Matching pixels between frames can be set to full transparency,
// allowing the previous frame's pixels to show through. We only do
// this for pixels that get mapped to the same quantized color so that
// the resulting image would be the same.
for (let i = 0; i < indexedFrame.length; i++) {
if (indexedFrame[i] === prevIndexedFrame[i]) {
indexedFrame[i] = transparentIndex;
}
}
// Write frame into the encoder
gif.writeFrame(indexedFrame, this.width, this.height, {
delay: gifFrameDelay,
transparent: true,
transparentIndex,
dispose: 1
});
}
prevIndexedFrame = originalIndexedFrame;
if (!silent) {
p.html(
'Rendered frame <b>' + i.toString() + '</b> out of ' + nFrames.toString()
);
}
// this just makes the process asynchronous, preventing
// that the encoding locks up the browser
await new Promise(resolve => setTimeout(resolve, 0));
}
gif.finish();
// Get a direct typed array view into the buffer to avoid copying it
const buffer = gif.bytesView();
const extension = 'gif';
const blob = new Blob([buffer], {
type: 'image/gif'
});
frames = [];
this._recording = false;
this.loop();
if (!silent){
p.html('Done. Downloading your gif!🌸');
if(notificationDuration > 0)
setTimeout(() => p.remove(), notificationDuration * 1000);
}
p5.prototype.downloadFile(blob, fileName, extension);
};
function _flipPixels(pixels, width, height) {
// extracting the pixels using readPixels returns
// an upside down image. we have to flip it back
// first. this solution is proposed by gman on
// this stack overflow answer:
// https://stackoverflow.com/questions/41969562/how-can-i-flip-the-result-of-webglrenderingcontext-readpixels
const halfHeight = parseInt(height / 2);
const bytesPerRow = width * 4;
// make a temp buffer to hold one row
const temp = new Uint8Array(width * 4);
for (let y = 0; y < halfHeight; ++y) {
const topOffset = y * bytesPerRow;
const bottomOffset = (height - y - 1) * bytesPerRow;
// make copy of a row on the top half
temp.set(pixels.subarray(topOffset, topOffset + bytesPerRow));
// copy a row from the bottom half to the top
pixels.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow);
// copy the copy of the top half row to the bottom half
pixels.set(temp, bottomOffset);
}
return pixels;
}
function _generateGlobalPalette(frames) {
// make an array the size of every possible color in every possible frame
// that is: width * height * frames.
let allColors = new Uint8Array(frames.length * frames[0].length);
// put every frame one after the other in sequence.
// this array will hold absolutely every pixel from the animation.
// the set function on the Uint8Array works super fast tho!
for (let f = 0; f < frames.length; f++) {
allColors.set(frames[f], f * frames[0].length);
}
// quantize this massive array into 256 colors and return it!
let colorPalette = quantize(allColors, 256, {
format: 'rgba4444',
oneBitAlpha: true
});
// when generating the palette, we have to leave space for 1 of the
// indices to be a random color that does not appear anywhere in our
// animation to use for transparency purposes. So, if the palette is full
// (has 256 colors), we overwrite the last one with a random, fully transparent
// color. Otherwise, we just push a new color into the palette the same way.
// this guarantees that when using the transparency index, there are no matches
// between some colors of the animation and the "holes" we want to dig on them,
// which would cause pieces of some frames to be transparent and thus look glitchy.
if (colorPalette.length === 256) {
colorPalette[colorPalette.length - 1] = [
Math.random() * 255,
Math.random() * 255,
Math.random() * 255,
0
];
} else {
colorPalette.push([
Math.random() * 255,
Math.random() * 255,
Math.random() * 255,
0
]);
}
return colorPalette;
}
/**
* Helper function for loading GIF-based images
*/
function _createGif(
arrayBuffer,
pImg,
successCallback,
failureCallback,
finishCallback
) {
const gifReader = new omggif.GifReader(arrayBuffer);
pImg.width = pImg.canvas.width = gifReader.width;
pImg.height = pImg.canvas.height = gifReader.height;
const frames = [];
const numFrames = gifReader.numFrames();
let framePixels = new Uint8ClampedArray(pImg.width * pImg.height * 4);
const loadGIFFrameIntoImage = (frameNum, gifReader) => {
try {
gifReader.decodeAndBlitFrameRGBA(frameNum, framePixels);
} catch (e) {
p5._friendlyFileLoadError(8, pImg.src);
if (typeof failureCallback === 'function') {
failureCallback(e);
} else {
console.error(e);
}
}
};
for (let j = 0; j < numFrames; j++) {
const frameInfo = gifReader.frameInfo(j);
const prevFrameData = pImg.drawingContext.getImageData(
0,
0,
pImg.width,
pImg.height
);
framePixels = prevFrameData.data.slice();
loadGIFFrameIntoImage(j, gifReader);
const imageData = new ImageData(framePixels, pImg.width, pImg.height);
pImg.drawingContext.putImageData(imageData, 0, 0);
let frameDelay = frameInfo.delay;
// To maintain the default of 10FPS when frameInfo.delay equals to 0
if (frameDelay === 0) {
frameDelay = 10;
}
frames.push({
image: pImg.drawingContext.getImageData(0, 0, pImg.width, pImg.height),
delay: frameDelay * 10 //GIF stores delay in one-hundredth of a second, shift to ms
});
// Some GIFs are encoded so that they expect the previous frame
// to be under the current frame. This can occur at a sub-frame level
//
// Values : 0 - No disposal specified. The decoder is
// not required to take any action.
// 1 - Do not dispose. The graphic is to be left
// in place.
// 2 - Restore to background color. The area used by the
// graphic must be restored to the background color.
// 3 - Restore to previous. The decoder is required to
// restore the area overwritten by the graphic with
// what was there prior to rendering the graphic.
// 4-7 - To be defined.
if (frameInfo.disposal === 2) {
// Restore background color
pImg.drawingContext.clearRect(
frameInfo.x,
frameInfo.y,
frameInfo.width,
frameInfo.height
);
} else if (frameInfo.disposal === 3) {
// Restore previous
pImg.drawingContext.putImageData(
prevFrameData,
0,
0,
frameInfo.x,
frameInfo.y,
frameInfo.width,
frameInfo.height
);
}
}
//Uses Netscape block encoding
//to repeat forever, this will be 0
//to repeat just once, this will be null
//to repeat N times (1<N), should contain integer for loop number
//this is changed to more usable values for us
//to repeat forever, loopCount = null
//everything else is just the number of loops
let loopLimit = gifReader.loopCount();
if (loopLimit === null) {
loopLimit = 1;
} else if (loopLimit === 0) {
loopLimit = null;
}
// we used the pImg for painting and saving during load
// so we have to reset it to the first frame
pImg.drawingContext.putImageData(frames[0].image, 0, 0);
if (frames.length > 1) {
pImg.gifProperties = {
displayIndex: 0,
loopLimit,
loopCount: 0,
frames,
numFrames,
playing: true,
timeDisplayed: 0,
lastChangeTime: 0
};
}
if (typeof successCallback === 'function') {
successCallback(pImg);
}
finishCallback();
}
/**
* @private
* @param {Constant} xAlign either LEFT, RIGHT or CENTER
* @param {Constant} yAlign either TOP, BOTTOM or CENTER
* @param {Number} dx
* @param {Number} dy
* @param {Number} dw
* @param {Number} dh
* @param {Number} sw
* @param {Number} sh
* @returns {Object}
*/
function _imageContain(xAlign, yAlign, dx, dy, dw, dh, sw, sh) {
const r = Math.max(sw / dw, sh / dh);
const [adjusted_dw, adjusted_dh] = [sw / r, sh / r];
let x = dx;
let y = dy;
if (xAlign === constants.CENTER) {
x += (dw - adjusted_dw) / 2;
} else if (xAlign === constants.RIGHT) {
x += dw - adjusted_dw;
}
if (yAlign === constants.CENTER) {
y += (dh - adjusted_dh) / 2;
} else if (yAlign === constants.BOTTOM) {
y += dh - adjusted_dh;
}
return { x, y, w: adjusted_dw, h: adjusted_dh };
}
/**
* @private
* @param {Constant} xAlign either LEFT, RIGHT or CENTER
* @param {Constant} yAlign either TOP, BOTTOM or CENTER
* @param {Number} dw
* @param {Number} dh
* @param {Number} sx
* @param {Number} sy
* @param {Number} sw
* @param {Number} sh
* @returns {Object}
*/
function _imageCover(xAlign, yAlign, dw, dh, sx, sy, sw, sh) {
const r = Math.max(dw / sw, dh / sh);
const [adjusted_sw, adjusted_sh] = [dw / r, dh / r];
let x = sx;
let y = sy;
if (xAlign === constants.CENTER) {
x += (sw - adjusted_sw) / 2;
} else if (xAlign === constants.RIGHT) {
x += sw - adjusted_sw;
}
if (yAlign === constants.CENTER) {
y += (sh - adjusted_sh) / 2;
} else if (yAlign === constants.BOTTOM) {
y += sh - adjusted_sh;
}
return { x, y, w: adjusted_sw, h: adjusted_sh };
}
/**
* @private
* @param {Constant} [fit] either CONTAIN or COVER
* @param {Constant} xAlign either LEFT, RIGHT or CENTER
* @param {Constant} yAlign either TOP, BOTTOM or CENTER
* @param {Number} dx
* @param {Number} dy
* @param {Number} dw
* @param {Number} dh
* @param {Number} sx
* @param {Number} sy
* @param {Number} sw
* @param {Number} sh
* @returns {Object}
*/
function _imageFit(fit, xAlign, yAlign, dx, dy, dw, dh, sx, sy, sw, sh) {
if (fit === constants.COVER) {
const { x, y, w, h } = _imageCover(xAlign, yAlign, dw, dh, sx, sy, sw, sh);
sx = x;
sy = y;
sw = w;
sh = h;
}
if (fit === constants.CONTAIN) {
const { x, y, w, h } = _imageContain(
xAlign,
yAlign,
dx,
dy,
dw,
dh,
sw,
sh
);
dx = x;
dy = y;
dw = w;
dh = h;
}
return { sx, sy, sw, sh, dx, dy, dw, dh };
}
/**
* Validates clipping params. Per drawImage spec sWidth and sHight cannot be
* negative or greater than image intrinsic width and height
* @private
* @param {Number} sVal
* @param {Number} iVal
* @returns {Number}
* @private
*/
function _sAssign(sVal, iVal) {
if (sVal > 0 && sVal < iVal) {
return sVal;
} else {
return iVal;
}
}
/**
* Draws an image to the canvas.
*
* The first parameter, `img`, is the source image to be drawn. `img` can be
* any of the following objects:
* - <a href="#/p5.Image">p5.Image</a>
* - <a href="#/p5.Element">p5.Element</a>
* - <a href="#/p5.Texture">p5.Texture</a>
* - <a href="#/p5.Framebuffer">p5.Framebuffer</a>
* - <a href="#/p5.FramebufferTexture">p5.FramebufferTexture</a>
*
* The second and third parameters, `dx` and `dy`, set the coordinates of the
* destination image's top left corner. See
* <a href="#/p5/imageMode">imageMode()</a> for other ways to position images.
*
* Here's a diagram that explains how optional parameters work in `image()`:
*
* <img src="assets/drawImage.png"></img>
*
* The fourth and fifth parameters, `dw` and `dh`, are optional. They set the
* the width and height to draw the destination image. By default, `image()`
* draws the full source image at its original size.
*
* The sixth and seventh parameters, `sx` and `sy`, are also optional.
* These coordinates define the top left corner of a subsection to draw from
* the source image.
*
* The eighth and ninth parameters, `sw` and `sh`, are also optional.
* They define the width and height of a subsection to draw from the source
* image. By default, `image()` draws the full subsection that begins at
* `(sx, sy)` and extends to the edges of the source image.
*
* The ninth parameter, `fit`, is also optional. It enables a subsection of
* the source image to be drawn without affecting its aspect ratio. If
* `CONTAIN` is passed, the full subsection will appear within the destination
* rectangle. If `COVER` is passed, the subsection will completely cover the
* destination rectangle. This may have the effect of zooming into the
* subsection.
*
* The tenth and eleventh paremeters, `xAlign` and `yAlign`, are also
* optional. They determine how to align the fitted subsection. `xAlign` can
* be set to either `LEFT`, `RIGHT`, or `CENTER`. `yAlign` can be set to
* either `TOP`, `BOTTOM`, or `CENTER`. By default, both `xAlign` and `yAlign`
* are set to `CENTER`.
*
* @method image
* @param {p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture} img image to display.
* @param {Number} x x-coordinate of the top-left corner of the image.
* @param {Number} y y-coordinate of the top-left corner of the image.
* @param {Number} [width] width to draw the image.
* @param {Number} [height] height to draw the image.
*
* @example
* <div>
* <code>
* let img;
*
* // Load the image.
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(50);
*
* // Draw the image.
* image(img, 0, 0);
*
* describe('An image of the underside of a white umbrella with a gridded ceiling above.');
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
*
* // Load the image.
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(50);
*
* // Draw the image.
* image(img, 10, 10);
*
* describe('An image of the underside of a white umbrella with a gridded ceiling above. The image has dark gray borders on its left and top.');
* }
* </code>
* </div>
*
* <div>
* <code>
* let img;
*
* // Load the image.
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(50);
*
* // Draw the image 50x50.
* image(img, 0, 0, 50, 50);