BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / image.js

image.js

subImage calc in image
timfa wsadhelios · pushed by timfa · 4 years ago
94864fd3 History
image.js 2.4 KiB Download Raw
1class image{
2 subImages = null;
3 subImagesPerRow = null;
4 loop = false;
5 chain = null;
6
7 g_image = null;
8
9 animationCycles = {};
10
11 constructor(image, subImgTotal = 1, perRow = 1, loop = false, chain = null)
12 {
13 subImgTotal = subImgTotal || 1;
14 perRow = perRow || 1;
15
16 this.subImages = subImgTotal;
17 this.subImagesPerRow = perRow;
18 this.g_image = image;
19 this.loop = loop;
20 this.chain = chain;
21
22 image.id="loadedImage";
23 document.body.append(image);
24 console.log("Image loaded: " + image.src);
25 }
26
27 draw(scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage)
28 {
29 var shouldDraw = true;
30
31 if(dx < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
32 shouldDraw = false;
33
34 if(dy < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
35 shouldDraw = false;
36
37 if(dx > scene.real_size.x + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
38 shouldDraw = false;
39
40 if(dy > scene.real_size.y + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
41 shouldDraw = false;
42
43 if(shouldDraw)
44 {
45 var context = scene.context;
46 context.save();
47 var oldAlpha = context.globalAlpha;
48 context.globalAlpha = alpha;
49
50 context.translate(dx, dy);
51 context.rotate(rotation * (Math.PI/180));
52
53 (mirrorX || mirrorY) && context.scale(mirrorX?-1:1, mirrorY?-1:1);
54
55 var subImageData = this.getSubImage(subImage);
56
57 context.drawImage(this.g_image, subImageData.sx, subImageData.sy, subImageData.sw, subImageData.sh, -dw/2, -dh/2, dw, dh);
58
59 context.restore();
60 context.globalAlpha = oldAlpha;
61 }
62 }
63
64 addAnimationCycle(label, cycle, loop, chain, chainDefaultIndex, chainSpeed)
65 {
66 this.animationCycles[label] =
67 {
68 frames: cycle,
69 loop: loop,
70 chain: chain,
71 chainDefaultIndex: chainDefaultIndex,
72 chainSpeed: chainSpeed
73 }
74 }
75
76 get width()
77 {
78 return this.g_image.width / this.subImagesPerRow;
79 }
80
81 get height()
82 {
83 return this.g_image.height / (Math.ceil(this.subImages / this.subImagesPerRow) + 0);
84 }
85
86 getSubImage(subImageIndex)
87 {
88 var subImage = Math.round(subImageIndex);
89 subImage %= this.subImages;
90
91 var c = subImage % this.subImagesPerRow;
92 var r = Math.floor(subImage / this.subImagesPerRow);
93 var sw = (this.g_image.width / this.subImagesPerRow);
94 var sh = (this.g_image.height / Math.ceil(this.subImages / this.subImagesPerRow));
95 var sx = sw * c;
96 var sy = sh * r;
97
98 return {sw : sw, sh : sh, sx: sx, sy: sy};
99 }
100}