BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / image.js

image.js

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