-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvas_ball.html
589 lines (589 loc) · 36 KB
/
canvas_ball.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="[MAZ01001.github.io] Colored bouncing ball screensaver with HTML5">
<meta name="author" content="MAZ01001">
<link rel="apple-touch-icon" sizes="180x180" href="../img/apple-touch-icon.png">
<link rel="icon" type="image/x-icon" href="../img/MAZ_logo.svg">
<link rel="icon" type="image/png" sizes="32x32" href="../img/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../img/favicon-16x16.png">
<link rel="manifest" href="../img/site.webmanifest">
<link rel="mask-icon" href="../img/safari-pinned-tab.svg" color="#ff9900">
<link rel="shortcut icon" href="../img/favicon.ico">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-config" content="../img/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<title>Screensaver</title>
<script>CSS?.registerProperty({name:"--rainbowanglecolor",syntax:"<angle>",inherits:false,initialValue:"120deg"});</script>
<style>
@keyframes rainbowcolor{
from{--rainbowanglecolor: 0deg;}
to{--rainbowanglecolor: 360deg;}
}
body{
--rainbowanglecolor: 120deg;
/* background-color: hsl(var(--rainbowanglecolor) 100% 50%); */
/* background-color: oklch(75% 0.127 var(--rainbowanglecolor)); */
background-color: #222;
padding: 0;
margin: 0 auto;
overflow: hidden;
animation: rainbowcolor 6s linear -2s infinite normal none paused;
}
canvas#canvas{
width: 100vw;
height: 100vh;
}
div#resizer{
position: absolute;
left: 50%;
top: 50%;
translate: -50% -50%;
display: flex;
flex-direction: column;
place-items: center;
place-content: center;
width: 80vw;
height: 75vh;
overflow: hidden;
background-color: #000A;
color: #0F0;
text-shadow: 0 0 .5rem #0A0;
font: 2rem "consolas", monospace;
border: 1px outset #000;
border-radius: 1rem;
user-select: none;
pointer-events: none;
opacity: 0;
visibility: hidden;
transition: opacity 1s ease-out, visibility 0s 1s;
}
div#resizer.show{
opacity: 1;
visibility: visible;
transition: opacity 100ms ease-in;
}
</style>
</head>
<body>
<canvas id="canvas">Your browser does not support the canvas element</canvas>
<div id="resizer"><p>Canvas <span id="resizeWidth">-</span> * <span id="resizeHeight">-</span> px</p></div>
<script>
"use strict";
//~ ______ _ _ _____
//~ | ___ \ \ | | __ \
//~ | |_/ / \| | | \/
//~ | /| . ` | | __
//~ | |\ \| |\ | |_\ \
//~ \_| \_\_| \_/\____/
/**
* # A class to get random numbers like `Math.random` but seed-able
* uses `MurmurHash3` for initial seed and `sfc32` for generating values
* @example new RNG("seed").value; //=> 0.8370377509475307
* @author MAZ <https://MAZ01001.GitHub.io/>
*/
const RNG=Object.freeze(class RNG{
/**@type {number} - [Private] First internal rng value*/_a_=0;
/**@type {number} - [Private] Second internal rng value*/_b_=0;
/**@type {number} - [Private] Third internal rng value*/_c_=0;
/**@type {number} - [Private] Fourth internal rng value*/_d_=0;
/**
* ## Get the current state
* four 32bit numbers (one 128bit number)
* @returns {readonly[number,number,number,number]} current state as four 32bit numbers (one 128bit number)
*/
get state(){
"use strict";
return Object.freeze([this._a_,this._b_,this._c_,this._d_]);
}
/**
* ## Create a new {@linkcode RNG} object
* @param {string?} seed - a string used as the seed (via `cyrb128`) - defaults to current timestamp (in hex)
* @returns {RNG} a new {@linkcode RNG} object with the given seed
* @example new RNG("seed").value; //=> 0.8370377509475307
* @throws {TypeError} - if {@linkcode seed} is not a string (not when it is null/undefined)
*/
constructor(seed){
"use strict";
if(seed==null)seed=Date.now().toString(0x10);
else if(typeof seed!=="string")throw new TypeError("[RNG::constructor] seedString is not a string");
[this._a_,this._b_,this._c_,this._d_]=RNG._generateSeed_(seed);
return Object.preventExtensions(this);
}
/**
* ## Creates a new {@linkcode RNG} object with given state
* @param {[number,number,number,number]} state - custom state (for sfc32) - must be four 32bit numbers
* @returns {RNG} new {@linkcode RNG} object with given state
* @throws {TypeError} if {@linkcode state} is not an array with four 32bit integers
*/
static from(state){
"use strict";
if(!Array.isArray(state))throw new TypeError("[RNG::from] state is not an array");
if(state.length!==4)throw new TypeError("[RNG::from] state is not an array with four values");
for(const num of state){
if(typeof num!=="number")throw new TypeError("[RNG::from] state is not an array with four numbers");
if(num<0||num>0xFFFFFFFF||!Number.isInteger(num))throw new TypeError("[RNG::from] state is not an array with four 32bit integers");
}
const rng=new RNG("");
[rng._a_,rng._b_,rng._c_,rng._d_]=state;
return rng;
}
/**
* ## [Private] Creates a 128 bit seed from the given string
* using `MurmurHash3`
* @param {string} str - a string
* @returns {readonly[number,number,number,number]} an array of four 32bit integers (one 128bit integer seed)
* @throws {TypeError} - if {@linkcode str} is not a string
*/
static _generateSeed_(str){
"use strict";
if(typeof str!=="string")throw new TypeError("[RNG::_generateSeed_] str is not a string");
let h=0x811C9DC5>>>0;
for(let i=0;i<str.length;i++){
const char=(k=>(k<<0xF)|(k>>>0x11))(Math.imul(str.charCodeAt(i),0xCC9E2D51));
h^=Math.imul(char,0x1B873593);
h=(h<<0xD)|(h>>>0x13);
h=(Math.imul(h,5)+0xE6546B64)|0;
}
h^=str.length;
const seed=()=>{
"use strict";
h^=h>>>0x10;
h=Math.imul(h,0x85EBCA6B);
h^=h>>>0xD;
h=Math.imul(h,0xC2B2AE35);
h^=h>>>0x10;
return h>>>0;
};
return Object.freeze([seed(),seed(),seed(),seed()]);
}
/**
* ## Get the next random 32bit value
* using `sfc32`
* @returns {number} a random 32bit unsigned integer
*/
get value32bit(){
"use strict";
this._a_|=0;
this._b_|=0;
this._c_|=0;
this._d_|=0;
const val=(((this._a_+this._b_)|0)+this._d_)|0;
this._d_=(++this._d_)|0;
this._a_=this._b_^(this._b_>>>9);
this._b_=(this._c_+(this._c_<<3))|0;
this._c_=(this._c_<<0x15)|(this._c_>>>0xB);
this._c_=(this._c_+val)|0;
return val>>>0;
}
/**
* ## Get the next random value
* @returns {number} a random value between 0 and 1 (inclusive)
*/
get val(){
"use strict";
return this.value32bit/0xFFFFFFFF;
}
/**
* ## Get the next random decimal value
* @returns {number} a random decimal value between 0 and 1 (0 inclusive and 1 exclusive)
*/
get dec(){
"use strict";
return this.value32bit/0x100000000;
}
/**
* ## Get a random boolean value
* @returns {boolean} a random boolean value
*/
get bool(){
"use strict";
return this.value32bit<0x10000;
}
/**
* ## Get the next random value and translate it to given range
* _range is inclusive and gives a float_
* @param {number} min - lower bound (inclusive)
* @param {number} max - upper bound (inclusive)
* @returns {number} random value within set range (if {@linkcode min} is not finite, returns {@linkcode min} and, if {@linkcode max} is not finite, returns {@linkcode max})
* @throws {TypeError} - if {@linkcode min} or {@linkcode max} are not numbers
*/
range(min,max){
"use strict";
if(typeof min!=="number")throw new TypeError("[RNG::range] min is not a number");
if(typeof max!=="number")throw new TypeError("[RNG::range] max is not a number");
if(!Number.isFinite(min))return min;
if(!Number.isFinite(max))return max;
if(min===max)return min;
return(this.value32bit*(max-min)+0xFFFFFFFF*min)/0xFFFFFFFF;
}
});
//~ _ _______ _ ___ _
//~ | | | | ___ \ | / _ \ | |
//~ | | | | |_/ / | / /_\ \_ __ __ _ _ _ _ __ ___ ___ _ __ | |_ ___
//~ | | | | /| | | _ | '__/ _` | | | | '_ ` _ \ / _ \ '_ \| __/ __|
//~ | |_| | |\ \| |____ | | | | | | (_| | |_| | | | | | | __/ | | | |_\__ \
//~ \___/\_| \_\_____/ \_| |_/_| \__, |\__,_|_| |_| |_|\___|_| |_|\__|___/
//~ __/ |
//~ |___/
// TODO remove `imgOverlay` and `colorSpeed`
// TODO create `color` for ball color which can be `transparent` and `hue(60)` (deg per sec) similar to `bgColor` with `rainbow(6s)`
// TODO create `delay` to add delay in milliseconds (float) after each draw call ~ can be used to set max FPS
const[//~ defaults
keepCanvas=false,
showFPS=false,
rng=new RNG(Math.trunc(Date.now()/0xEA60).toString(0x10)),
hideOutline=false,
ballSizePercent=.2,
ballSpeed=0xF0,
colorSpeed=0x3C,
colorRGB=false,
ballImg=null,
ballImgPixelArt=false,
ballImgOverlay=false,
ballText="",
ballTextFill="#0f0",
ballTextStroke="#000",
ballTextStrokeWidth=1,
ballTextHeight=.4,
ballTextFontFamily="\"Times New Roman\", Times, serif",
ballTextFontStyle="normal",
ballTextFontSmallCaps=false,
ballTextFontWeight="normal",
ballTextFontStretch="normal",
]=(()=>{//~ overrides (fallback to default via undefined)
"use strict";
const args=new URLSearchParams(window.location.search);
let _tmpVal_=null,
_tmpNum_=NaN;
if((_tmpVal_=args.get("bgColor"))!=null){
if(_tmpVal_.startsWith("rainbow")){
const bgRGB=args.get("bgRGB");
document.body.style.backgroundColor=bgRGB!=null&&(bgRGB===""||bgRGB==="1"||bgRGB==="true")?"hsl(var(--rainbowanglecolor) 100% 50%)":"oklch(75% 0.127 var(--rainbowanglecolor))";
document.body.style.animationPlayState="running";
const rainbowMatch=_tmpVal_.match(/^rainbow\(([+-]?)([1-9][0-9]*)(s|ms)?\)$/);
if(rainbowMatch){
if(rainbowMatch[1]==='-'){document.body.style.animationDirection="reverse";}
if(Number.isFinite(_tmpNum_=Number(rainbowMatch[2]))){
document.body.style.animationDuration=rainbowMatch[2]+(rainbowMatch[3]??"s");
document.body.style.animationDelay="-"+String(rainbowMatch[1]==='-'?_tmpNum_*2/3:_tmpNum_/3)+(rainbowMatch[3]??"s");
}
}
}else document.body.style.backgroundColor=_tmpVal_;
}
return[
(_tmpVal_=args.get("keepCanvas"))==null?undefined:(_tmpVal_===""||_tmpVal_==="1"||_tmpVal_==="true"),
(_tmpVal_=args.get("fps"))==null?undefined:(_tmpVal_===""||_tmpVal_==="1"||_tmpVal_==="true"),
(_tmpVal_=args.get("seed"))==null?undefined:new RNG(_tmpVal_),
(_tmpVal_=args.get("hideOutline"))==null?undefined:(_tmpVal_===""||_tmpVal_==="1"||_tmpVal_==="true"),
(_tmpVal_=args.get("ballSize"))==null?undefined:(Number.isNaN(_tmpNum_=Number(_tmpVal_))||_tmpNum_>1||_tmpNum_<0?undefined:_tmpNum_),
(_tmpVal_=args.get("ballSpeed"))==null?undefined:(Number.isFinite(_tmpNum_=Number(_tmpVal_))?_tmpNum_:undefined),
(_tmpVal_=args.get("colorSpeed"))==null?undefined:(Number.isFinite(_tmpNum_=Number(_tmpVal_))?_tmpNum_:undefined),
(_tmpVal_=args.get("colorRGB"))==null?undefined:(_tmpVal_===""||_tmpVal_==="1"||_tmpVal_==="true"),
(_tmpVal_=args.get("img"))==null?undefined:(_tmpVal_.length>0?_tmpVal_:undefined),
(_tmpVal_=args.get("imgPixelArt"))==null?undefined:(_tmpVal_===""||_tmpVal_==="1"||_tmpVal_==="true"),
(_tmpVal_=args.get("imgOverlay"))==null?undefined:(_tmpVal_===""||_tmpVal_==="1"||_tmpVal_==="true"),
(_tmpVal_=args.get("txt"))==null?undefined:(_tmpVal_.length>0?_tmpVal_:undefined),
(_tmpVal_=args.get("txtFill"))==null?undefined:(_tmpVal_.length>0?_tmpVal_:undefined),
(_tmpVal_=args.get("txtLine"))==null?undefined:(_tmpVal_.length>0?_tmpVal_:undefined),
(_tmpVal_=args.get("txtLineWidth"))==null?undefined:(Number.isFinite(_tmpNum_=Number(_tmpVal_))&&_tmpNum_>=0?_tmpNum_:undefined),
(_tmpVal_=args.get("txtHeight"))==null?undefined:(Number.isFinite(_tmpNum_=Number(_tmpVal_))&&_tmpNum_>=0?_tmpNum_:undefined),
(_tmpVal_=args.get("txtFont"))==null?undefined:(_tmpVal_.length>0?_tmpVal_:undefined),
(_tmpVal_=args.get("txtStyle"))==null?undefined:(_tmpVal_.length>0?_tmpVal_:undefined),
(_tmpVal_=args.get("txtSmallCaps"))==null?undefined:(_tmpVal_===""||_tmpVal_==="1"||_tmpVal_==="true"),
(_tmpVal_=args.get("txtWeight"))==null?undefined:(/^(?:[a-zA-Z-]+|[1-9][0-9]{0,2}|1000)$/.test(_tmpVal_)?_tmpVal_:undefined),
(_tmpVal_=args.get("txtStretch"))==null?undefined:(/^[a-zA-Z-]+$/.test(_tmpVal_)?_tmpVal_:undefined)
];
})();
//~ _____ _
//~ / ___| | |
//~ \ `--. ___| |_ _ _ _ __
//~ `--. \/ _ \ __| | | | '_ \
//~ /\__/ / __/ |_| |_| | |_) |
//~ \____/ \___|\__|\__,_| .__/
//~ | |
//~ |_|
const canvasHTML=document.getElementById("canvas"),
resizer=document.getElementById("resizer"),
resizeWidth=document.getElementById("resizeWidth"),
resizeHeight=document.getElementById("resizeHeight"),
img=document.createElement("img"),
canvas=canvasHTML.getContext("2d",{colorSpace:"srgb"}),
/**@type {[string, string]} [ font size (with unit), font family/s ]*/
canvasFont=(font=>{
"use strict";
const[,size,family]=font.match(/^([0-9]+(?:[A-Za-z]+)?) (.+)$/);
return[size,family];
})(canvas.font),
docFontSize=Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize);
let resizing=false,
resizeTimeout=NaN;
canvasHTML.width=Math.trunc(window.innerWidth*window.devicePixelRatio);
canvasHTML.height=Math.trunc(window.innerHeight*window.devicePixelRatio);
window.addEventListener("resize",()=>{
"use strict";
clearTimeout(resizeTimeout);
resizer.classList.toggle("show",resizing=true);
resizeWidth.textContent=Math.trunc(window.innerWidth*window.devicePixelRatio).toString();
resizeHeight.textContent=Math.trunc(window.innerHeight*window.devicePixelRatio).toString();
resizeTimeout=setTimeout(()=>{
canvasHTML.width=Math.trunc(window.innerWidth*window.devicePixelRatio);
canvasHTML.height=Math.trunc(window.innerHeight*window.devicePixelRatio);
resizer.classList.toggle("show",resizing=false);
},0x1F4);
},{passive:true});
let direction=[rng.bool,rng.bool],
position=(ballSize=>[
rng.range(ballSize,canvasHTML.width-ballSize),
rng.range(ballSize,canvasHTML.height-ballSize)
])((canvasHTML.width>canvasHTML.height?canvasHTML.height:canvasHTML.width)*ballSizePercent*0.5),
lastFrameTime=0,
colorHue=0x78,
drawImg=false,
/** last few frame times (fixed to size 8) */
fps=new class{
/** @param {number} size - size of the stored list */
constructor(size){
this._arr_=new Float64Array(size);
this._avg_=(this._len_=(this._pos_=0));
}
/**
* ## Add a new frame time to the list (converted to FPS and pre-calculate rounded sum of all stored FPS)
* @param {number} ft - new frame time (time in milliseconds from last to current frame) to add to the list
* @returns {number} {@linkcode ft} (unchanged) for chaining
*/
add(ft){
this._arr_[this._pos_=(this._pos_+1)%this._arr_.length]=0x3E8/ft;
if(this._len_<this._arr_.length)this._len_++;
this._avg_=0;
for(let i=0;i<this._len_;i++)this._avg_+=this._arr_[i];
this._avg_=Math.round(this._avg_/this._arr_.length);
return ft;
}
valueOf(){return this._avg_;}
toString(){return this._avg_.toString();}
}(8);
if(ballImg!=null){
img.loading="eager";
img.addEventListener("load",()=>void(drawImg=true),{passive:true,once:true});
img.src=ballImg;
}
//~ ______
//~ | _ \
//~ | | | |_ __ __ ___ __
//~ | | | | '__/ _` \ \ /\ / /
//~ | |/ /| | | (_| |\ V V /
//~ |___/ |_| \__,_| \_/\_/
/**
* ## Renders one frame on {@linkcode canvas}
* @param {number} deltaTimeSec - the time in seconds from last to current frame
*/
const draw=deltaTimeSec=>{
"use strict";
const ballRadius=((canvasHTML.width>canvasHTML.height?canvasHTML.height:canvasHTML.width)*(ballSizePercent>0?ballSizePercent:.2))*0.5;
//~ ball position (possibly overshoot)
if(ballSizePercent===1&&canvasHTML.width<canvasHTML.height)position[0]=ballRadius;
else position[0]=position[0]+ballSpeed*deltaTimeSec*(direction[0]?1:-1);
if(ballSizePercent===1&&canvasHTML.height<canvasHTML.width)position[1]=ballRadius;
else position[1]=position[1]+ballSpeed*deltaTimeSec*(direction[1]?1:-1);
//~ ball trajectory calculation (clamp position)
const limitRight=canvasHTML.width-ballRadius,
limitDown=canvasHTML.height-ballRadius,
boundWidth=canvasHTML.width-(ballRadius*2),
boundHeight=canvasHTML.height-(ballRadius*2);
//~ X overshoot right/left
if(position[0]>=limitRight){
const xFields=Math.floor((position[0]-ballRadius)/boundWidth);
position[0]=ballRadius+((position[0]-ballRadius)%boundWidth);
if(xFields&1===1)position[0]=canvasHTML.width-position[0];
direction[0]=false;
}else if(position[0]<=ballRadius){
const xFields=Math.floor((ballRadius-position[0])/boundWidth);
position[0]=ballRadius+((ballRadius-position[0])%boundWidth);
if(xFields&1===0)position[0]=canvasHTML.width-position[0];
direction[0]=true;
}
//~ Y overshoot down/up
if(position[1]>=limitDown){
const yFields=Math.floor((position[1]-ballRadius)/boundHeight);
position[1]=ballRadius+((position[1]-ballRadius)%boundHeight);
if(yFields&1===1)position[1]=canvasHTML.height-position[1];
direction[1]=false;
}else if(position[1]<=ballRadius){
const yFields=Math.floor((ballRadius-position[1])/boundHeight);
position[1]=ballRadius+((ballRadius-position[1])%boundHeight);
if(yFields&1===0)position[1]=canvasHTML.height-position[1];
direction[1]=true;
}
// TODO fade(alphaMultiplier) ← 0-1 float
//! all bellow blocks have the same result → fade out but never full transparent
//? ↓ bad - creating image data every frame - better with `{willReadFrequently:true}` in first `getContext("2d")` but canvas will then be on CPU only
//// const cnvColor=canvas.getImageData(0,0,canvasHTML.width,canvasHTML.height,{colorSpace:"srgb"});
//// for(let i=3;i<cnvColor.data.length;i+=4)cnvColor.data[i]*=.95;
//// canvas.putImageData(cnvColor,0,0);
//? ↓ good
//// const gco=canvas.globalCompositeOperation;
//// canvas.globalCompositeOperation="destination-in";
//// canvas.fillStyle="rgb(0 0 0 / 0.95)";
//// canvas.fillRect(0,0,canvasHTML.width,canvasHTML.height);
//// canvas.globalCompositeOperation=gco;
//? ↓ better
//// const gco=canvas.globalCompositeOperation;
//// canvas.globalCompositeOperation="copy";
//// canvas.globalAlpha=.95;
//// canvas.drawImage(canvasHTML,0,0);
//// canvas.globalCompositeOperation=gco;
//// canvas.globalAlpha=1;
//! can't work (with canvas alone) because of how alpha gets multiplied and float precision so it never reaches zero alpha
// TODO => offscreen canvas the size of the ball/img with alpha and draw that on the main canvas at current position (aligned center on position)
if(!keepCanvas)canvas.clearRect(0,0,canvasHTML.width,canvasHTML.height);
if(canvas.imageSmoothingEnabled=!ballImgPixelArt)canvas.imageSmoothingQuality="high";
// TODO add support for GIFs - see https://github.com/MAZ01001/GIF_decoder
//~ draw ball &/ img
if(ballSizePercent>0){
const[imgW,imgH]=(()=>{
if(img.width>img.height)return[ballRadius,ballRadius*(img.height/img.width)];
if(img.width<img.height)return[ballRadius*(img.width/img.height),ballRadius];
return[ballRadius,ballRadius];
})();
if(drawImg&&!ballImgOverlay)canvas.drawImage(img,position[0]-imgW,position[1]-imgH,imgW*2,imgH*2);
else{
canvas.beginPath();
canvas.arc(position[0],position[1],ballRadius,0,Math.PI*2);
if(!hideOutline){
canvas.strokeStyle="#000";
canvas.lineWidth=3;
canvas.stroke();
}
colorHue=(colorHue+colorSpeed*deltaTimeSec)%0x168;
canvas.fillStyle=colorRGB?`hsl(${colorHue} 100% 50%)`:`oklch(75% 0.127 ${colorHue})`;
canvas.fill();
if(drawImg){
canvas.beginPath();
canvas.arc(position[0],position[1],ballRadius,0,Math.PI*2);
canvas.closePath();
canvas.save();
canvas.clip();
canvas.drawImage(img,position[0]-imgW,position[1]-imgH,imgW*2,imgH*2);
canvas.restore();
}
}
}
//~ draw text on ball/img (or only draw text when ballSizePercent is 0 or below)
// TODO add support for multiline text ("\n") - get default line-height via canvasHTMLCSS (live computed style map of canvasHTML) and add URL param for line-height (percent of ball-text-font-size)
if(ballText!==""){
canvas.beginPath();
const ballTextFontSize=ballRadius*2*ballTextHeight;
canvas.font=`${ballTextFontStyle} ${ballTextFontSmallCaps?"small-caps":"normal"} ${ballTextFontWeight} ${ballTextFontStretch} ${ballTextFontSize+"px"} ${ballTextFontFamily}`;
canvas.textAlign="center";
canvas.textBaseline="middle";
if(ballTextStrokeWidth!==0){
canvas.strokeStyle=ballTextStroke;
canvas.lineWidth=ballTextStrokeWidth*ballTextFontSize/0xF;
canvas.strokeText(ballText,position[0],position[1]);
}
canvas.fillStyle=ballTextFill;
canvas.fillText(ballText,position[0],position[1]);
}
//~ draw fps
if(showFPS){
const txt=`fps ${fps.toString().padStart(3,' ')}`;
canvas.font="20px consolas,monospace";
canvas.textAlign="left";
canvas.textBaseline="top";
canvas.strokeStyle="#000";
if(keepCanvas){
canvas.beginPath();
canvas.lineCap="round";
canvas.lineWidth=24;
canvas.moveTo(23,25);
canvas.lineTo(canvas.measureText(txt).width+7,25);
canvas.stroke();
}else{
canvas.lineWidth=2;
canvas.strokeText(txt,15,15);
}
canvas.fillStyle="#0F0";
canvas.fillText(txt,15,15);
}
}
//~ _
//~ | |
//~ | | ___ ___ _ __
//~ | | / _ \ / _ \| '_ \
//~ | |___| (_) | (_) | |_) |
//~ \_____/\___/ \___/| .__/
//~ | |
//~ |_|
let _previousFrameTimestamp_=0;
const animationLoop=frameTimestamp=>{
"use strict";
if(!resizing&&frameTimestamp!==_previousFrameTimestamp_){
const frameTime=frameTimestamp-_previousFrameTimestamp_;
//~ wait 100ms before starting to draw ~ let fps stabilize
if(frameTimestamp>0x64)draw(fps.add(frameTime)/0x3E8);
}
_previousFrameTimestamp_=frameTimestamp;
window.requestAnimationFrame(animationLoop);
}
window.requestAnimationFrame(animationLoop);
//~ _____ __
//~ |_ _| / _|
//~ | | _ __ | |_ ___
//~ | || '_ \| _/ _ \
//~ _| || | | | || (_) |
//~ \___/_| |_|_| \___/
console.groupCollapsed(
"%c%s",
"background-color:#000;color:#0F0;font-size:larger",
"available URL parameters"
);
console.log(
"You might need to expand the console window to see the entire table.\n%c%s",
"background-color:#000;color:#0F0;font-family:consolas,monospace;white-space:pre;",
[
"+----------------+--------------------------------------------------------------+-----------------------------------+-----------------------------------------------------------+",
"| parameter | description | default value | possible values |",
"+----------------+--------------------------------------------------------------+-----------------------------------+-----------------------------------------------------------+",
"| `bgColor` | set the background color of the page (can be transparent) | `#222` (dark grey) | CSS color like `black` or `transparent` |",
"| | or a rainbow color animation | (rainbow default speed is `6s`) | or `rainbow` or `rainbow([+|-]speed[s|ms])` |",
"| | with the speed in seconds or milliseconds as parameter | | (`speed` is a finite integer) |",
"| `bgRGB` | if set, uses HSL instead of OKLCH color model for `bgColor` | NO | empty or `1` for YES and `0` or else NO |",
"| `keepCanvas` | if set, doesn't clear the canvas every frame | NO | empty or `1` for YES and `0` or else NO |",
"| `fps` | shows frames per second in the top left corner | NO | empty or `1` for YES and `0` or else NO |",
"| `seed` | set the seed for RNG | minute timestamp in hex | anything (even empty) |",
"| -------------- | ------------------------------------------------------------ | --------------------------------- | --------------------------------------------------------- |",
"| `ballSize` | set the ball size (%) relative to the smaller window size | `0.2` | decimal number between `0` and `1` (inclusive) |",
"| `ballSpeed` | set the speed of the ball in pixels per second | `240` | decimal number |",
"| `hideOutline` | if set, hides the black outline around ball/image | NO | empty or `1` for YES and `0` or else NO |",
"| -------------- | ------------------------------------------------------------ | --------------------------------- | --------------------------------------------------------- |",
"| `colorSpeed` | set the speed of the color shift in degrees per second | `60` | decimal number |",
"| `colorRGB` | if set, uses HSL instead of OKLCH color model for the ball | NO | empty or `1` for YES and `0` or else NO |",
"| -------------- | ------------------------------------------------------------ | --------------------------------- | --------------------------------------------------------- |",
"| `img` | put an image over the ball | none | HTML image source (URL) |",
"| | (if the image doesn't replace the ball, it gets cut to fit) | | |",
"| `imgPixelArt` | if set, enables better scaling filter for pixel art | NO | empty or `1` for YES and `0` or else NO |",
"| `imgOverlay` | if set, overlays the `img` instead of replacing the ball | NO | empty or `1` for YES and `0` or else NO |",
"| -------------- | ------------------------------------------------------------ | --------------------------------- | --------------------------------------------------------- |",
"| `txt` | (single line) text to put over the ball/image | none | single line text |",
"| `txtHeight` | set the `txt` size (height) relative to the size of the ball | `0.4` | positive decimal number |",
"| | with no ball/image it is relative to the smaller window size | | |",
"| `txtFill` | `txt` fill color (CSS color, canvas gradient/pattern) | `#0F0` (green) | CSS color / canvas gradient or pattern |",
"| `txtLine` | `txt` outline color (CSS color, canvas gradient/pattern) | `#000` (black) | CSS color / canvas gradient or pattern |",
"| `txtLineWidth` | set the width of `txt` outline relative to `txtHeight` | `1` | positive decimal number |",
"| -------------- | ------------------------------------------------------------ | --------------------------------- | --------------------------------------------------------- |",
'| `txtFont` | set the font of the `txt` (CSS font family) | `"Times New Roman", Times, serif` | CSS font-family, like `sans-serif` |',
"| `txtWeight` | set the boldness of the `txt` | `normal` | CSS font-weight, like `bold` or `1` to `1000` (inclusive) |",
"| `txtSmallCaps` | if set, uses small-caps for the `txt` | NO | empty or `1` for YES and `0` or else NO |",
"| | (scaled down uppercase for lowercase letters) | | |",
"| `txtStyle` | set the font style of the `txt` (italic/oblique) | `normal` | CSS font-style, like `italic` or `oblique` |",
"| `txtStretch` | set the horizontal stretch of the `txt` | `normal` | CSS font-stretch, but only keywords and not percentages |",
"+----------------+--------------------------------------------------------------+-----------------------------------+-----------------------------------------------------------+",
].join('\n')
);
console.groupEnd();
</script>
</body>
</html>