BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / image.js

image.js

1e920c27 History
image.js 2.5 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 addAnimationCycle (label, cycle, loop, chain, chainDefaultIndex, chainSpeed)
69 {
70 this.animationCycles[label] =
71 {
72 frames: cycle,
73 loop: loop,
74 chain: chain,
75 chainDefaultIndex: chainDefaultIndex,
76 chainSpeed: chainSpeed
77 };
78 }
79
80 get width ()
81 {
82 if (this.cacheWidth < 0)
83 this.g_image.width / this.subImagesPerRow;
84
85 return this.cacheWidth;
86 }
87
88 get height ()
89 {
90 if (this.cacheHeight < 0)
91 this.g_image.height / (Math.ceil(this.subImages / this.subImagesPerRow) + 0);
92
93 return this.cacheHeight;
94 }
95
96 cacheWidth = -1;
97 cacheHeight = -1;
98
99 getSubImage (subImageIndex)
100 {
101 var subImage = Math.round(subImageIndex);
102 subImage %= this.subImages;
103
104 var c = subImage % this.subImagesPerRow;
105 var r = Math.floor(subImage / this.subImagesPerRow);
106 var sw = (this.g_image.width / this.subImagesPerRow);
107 var sh = (this.g_image.height / Math.ceil(this.subImages / this.subImagesPerRow));
108 var sx = sw * c;
109 var sy = sh * r;
110
111 return { sw: sw, sh: sh, sx: sx, sy: sy };
112 }
113}