tinieanim 0.0.0-stage → 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TKien2
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # TinieAnim
2
+ A JavaScript animation library
3
+
4
+ ![version](https://img.shields.io/badge/version-0.1.0--alpha.1-blue?style=for-the-badge)
5
+
6
+ ![license](https://img.shields.io/badge/license-MIT-blue)
7
+ ![status](https://img.shields.io/badge/status-WIP-green)
8
+
9
+ # Important Notice
10
+ This library is currently **unstable**.
11
+
12
+ **Not recommended** for production use.
13
+
14
+ Documentation is not available yet.
package/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * TinieAnim
3
+ * Copyright (c) 2026 TKien2
4
+ * Licensed under the MIT License.
5
+ */
6
+ export {Rectangle, Arc, Circle, Line, Arrow, Group} from "./src/shapes.js"
7
+ export {Vector2, Coordinates2, Matrix} from "./src/math.js"
8
+ export {createScreen, Render} from "./src/render.js"
9
+ export {animation} from "./src/animation.js"
10
+ export {COLORS} from "./src/constants.js"
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "tinieanim",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "A JavaScript animation library",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Tkien2/TinieAnim.git"
12
+ },
13
+ "keywords": [
14
+ "javascript",
15
+ "animation",
16
+ "tinieanim",
17
+ "tkien2"
18
+ ],
19
+ "author": "TKien2",
20
+ "license": "MIT",
21
+ "type": "module",
22
+ "bugs": {
23
+ "url": "https://github.com/Tkien2/TinieAnim/issues"
24
+ },
25
+ "homepage": "https://github.com/Tkien2/TinieAnim#readme"
26
+ }
@@ -0,0 +1,44 @@
1
+ import { BinarySearch, CubicBezierCurve } from "./math.js"
2
+ export const animation = {
3
+ LINEAR: "LINEAR",
4
+ EASE_IN_OUT: "EASE_IN_OUT",
5
+ EASE_IN: "EASE_IN",
6
+ EASE_OUT: "EASE_OUT",
7
+ }
8
+ function easeInOut(t, isX = true){
9
+ return CubicBezierCurve(t, isX, [[0.5,0],[0.5,1]])
10
+ }
11
+ function easeIn(t, isX = true){
12
+ return CubicBezierCurve(t, isX, [[0.5,0],[1,1]])
13
+ }
14
+ function easeOut(t, isX = true){
15
+ return CubicBezierCurve(t, isX, [[0,0],[0.5,1]])
16
+ }
17
+ function motion(t, motionFunction){
18
+ if(t>=0 && t<=1){
19
+ let i = BinarySearch(t, motionFunction)
20
+ return motionFunction(i, false)
21
+ }
22
+ }
23
+ function easeInOutMotion(t){
24
+ return motion(t, easeInOut)
25
+ }
26
+ function easeInMotion(t){
27
+ return motion(t, easeIn)
28
+ }
29
+ function easeOutMotion(t){
30
+ return motion(t, easeOut)
31
+ }
32
+ export function timingFunction(t, timingFunction){
33
+ if(t>=0 && t<=1){
34
+ if(timingFunction == animation.LINEAR){
35
+ return t
36
+ } else if(timingFunction == animation.EASE_IN_OUT){
37
+ return easeInOutMotion(t)
38
+ } else if(timingFunction == animation.EASE_IN){
39
+ return easeInMotion(t)
40
+ } else if(timingFunction == animation.EASE_OUT){
41
+ return easeOutMotion(t)
42
+ }
43
+ }
44
+ }
@@ -0,0 +1,11 @@
1
+ export const COLORS = {
2
+ White: "#FFFFFF",
3
+ Black: "#000000",
4
+ Red: "#FF3838",
5
+ Orange: "#FFA538",
6
+ Yellow: "#FFFC38",
7
+ Green: "#38FF3B",
8
+ Blue: "#385DFF",
9
+ Purple: "#9B38FF",
10
+ Void: "#141516",
11
+ }
package/src/math.js ADDED
@@ -0,0 +1,195 @@
1
+ export class Matrix{
2
+ #matrix
3
+ #isValid = true
4
+ constructor(matrix){
5
+ this.#matrix = matrix
6
+ this.#checkMatrix()
7
+ }
8
+ setMatrix(matrix){
9
+ if(Array.isArray(matrix)){
10
+ this.#matrix = matrix
11
+ } else{
12
+ throw TypeError("Matrix must be an array")
13
+ }
14
+ }
15
+ getMatrix(){
16
+ return this.#matrix
17
+ }
18
+ #checkMatrix(){
19
+ if(!Array.isArray(this.#matrix) || this.#matrix.length <= 0){
20
+ console.error("Matrix must be an Array and can not be empty");
21
+ this.#isValid = false;
22
+ return
23
+ }
24
+ let col = this.#matrix[0].length
25
+ for(const row of this.#matrix){
26
+ if(Array.isArray(row)){
27
+ if(row.length !== col){
28
+ console.error("All rows must have the same length (columns)")
29
+ this.#isValid = false;
30
+ return
31
+ }
32
+ for(const value of row){
33
+ if(typeof value !== 'number' || !Number.isFinite(value)){
34
+ console.error("Value is not valid",this.#matrix)
35
+ this.#isValid = false
36
+ return
37
+ }
38
+ }
39
+ } else{
40
+ console.error(`Matrix must be an Array. ${row} is not an Array`);
41
+ this.#isValid = false;
42
+ return
43
+ }
44
+ }
45
+ }
46
+ isValid(){
47
+ return this.#isValid
48
+ }
49
+ changeValue(rowIndex, columnIndex, value){
50
+ if(Number.isFinite(rowIndex) && Number.isFinite(columnIndex) && Number.isFinite(value)){
51
+ this.#matrix[rowIndex][columnIndex] = value
52
+ } else{
53
+ console.error("All parameters must be finite numbers")
54
+ }
55
+ }
56
+ multiply(matrix){
57
+ let A = {
58
+ rows: this.#matrix.length,
59
+ cols: this.#matrix[0].length
60
+ }
61
+ let B = {
62
+ rows: matrix.getMatrix().length,
63
+ cols: matrix.getMatrix()[0].length
64
+ }
65
+ if(this.isValid() && matrix.isValid()){
66
+ if(A.cols === B.rows){
67
+ let newMatrix = []
68
+ for(let rA = 0; rA < A.rows; rA++){
69
+ let rC = []
70
+ for(let cB = 0; cB < B.cols; cB++){
71
+ let sum = 0
72
+ for(let cA = 0; cA < A.cols; cA++){
73
+ sum += this.#matrix[rA][cA]*matrix.getMatrix()[cA][cB]
74
+ }
75
+ rC.push(sum)
76
+ }
77
+ newMatrix.push(rC)
78
+ }
79
+ return new Matrix(newMatrix)
80
+ }
81
+ }
82
+ console.error("Can not multiply these matrixes")
83
+ }
84
+ }
85
+ export class Vector2{
86
+ constructor(x,y){
87
+ this.x = x
88
+ this.y = y
89
+ }
90
+ setVector(x,y){
91
+ if(Number.isFinite(x) && Number.isFinite(y)){
92
+ this.x = x
93
+ this.y = y
94
+ } else{
95
+ throw TypeError("x and y must be finite numbers")
96
+ }
97
+ }
98
+ getLength(){
99
+ return Math.sqrt(this.x*this.x + this.y*this.y)
100
+ }
101
+ add(vector2){
102
+ return new Vector2(vector2.x + this.x, vector2.y + this.y)
103
+ }
104
+ subtract(vector2){
105
+ return new Vector2(this.x - vector2.x, this.y - vector2.y)
106
+ }
107
+ multiply(scalar){
108
+ return new Vector2(this.x*scalar, this.y*scalar)
109
+ }
110
+ toMatrix(){
111
+ return new Matrix([[this.x],[this.y]])
112
+ }
113
+ copy(){
114
+ return this
115
+ }
116
+ dot(vector){
117
+ if(vector.constructor.name === "Vector2"){
118
+ return this.x*vector.x + this.y*vector.y
119
+ } else{
120
+ throw TypeError("'vector' must be a vector", vector)
121
+ }
122
+ }
123
+ isEqual(vector){
124
+ if(vector.constructor.name === "Vector2"){
125
+ return this.x == vector.x && this.y == vector.y
126
+ }else{
127
+ throw TypeError("'vector' must be a vector", vector)
128
+ }
129
+ }
130
+ }
131
+ export class Coordinates2{
132
+ constructor(x,y){
133
+ this.x = x
134
+ this.y = y
135
+ }
136
+ setCoordinates2(x,y){
137
+ if(Number.isFinite(x) && Number.isFinite(y)){
138
+ this.x = x
139
+ this.y = y
140
+ } else{
141
+ throw TypeError("x and y must be finite numbers")
142
+ }
143
+ }
144
+ subtract(coords2){
145
+ return new Vector2(this.x - coords2.x, this.y - coords2.y)
146
+ }
147
+ shift(vector2){
148
+ return new Coordinates2(this.x + vector2.x, this.y + vector2.y)
149
+ }
150
+ copy(){
151
+ return this
152
+ }
153
+ isEqual(coords){
154
+ if(coords.constructor.name === "Coordinates2"){
155
+ return this.x == coords.x && this.y == coords.y
156
+ }else{
157
+ throw TypeError("'coords' must be a vector", coords)
158
+ }
159
+ }
160
+ }
161
+ export function CubicBezierCurve(t, isX = true, controlPoints = [[0.5,0],[0.5,1]]){
162
+ if ((controlPoints[0][0] >= 0 && controlPoints[0][0] <=1) && (controlPoints[1][0] >= 0 && controlPoints[1][0] <=1)){
163
+ if(isX){
164
+ return 3*Math.pow(1-t,2)*t*controlPoints[0][0] + 3*(1-t)*t*t*controlPoints[1][0] + t*t*t
165
+ } else{
166
+ return 3*Math.pow(1-t,2)*t*controlPoints[0][1] + 3*(1-t)*t*t*controlPoints[1][1] + t*t*t
167
+ }
168
+ } else{
169
+ // giới hạn chỉ cho phép hàm Bezier không có cực trị
170
+ console.error("The x-coordinate of the control point must be within the interval (0, 1)")
171
+ }
172
+ }
173
+ //đơn điệu + đồng biến
174
+ export function BinarySearch(target, func, min=0, max=1, decimalPoint = 6){
175
+ let l = min
176
+ let r = max
177
+ let i = (r + l)/2
178
+ let value = null
179
+ const factor = 10**decimalPoint
180
+ target = Math.round(target*factor)/factor
181
+ for(let k = 0; k<=30; k++){
182
+ value = func(i)
183
+ if(value > target){
184
+ r = i
185
+ } else {
186
+ l = i
187
+ }
188
+ if(Math.round(value*factor)/factor == target){
189
+ return i
190
+ }
191
+ i = (r + l)/2
192
+ }
193
+ console.warn("Can not find the value you are looking for")
194
+ return undefined
195
+ }
package/src/render.js ADDED
@@ -0,0 +1,226 @@
1
+ import { animation, timingFunction } from "./animation.js"
2
+ import { Coordinates2, Matrix } from "./math.js"
3
+ export function createScreen(width, height, parent = null, scale = 1, flipYAxis = true){
4
+ const canvas = document.createElement("canvas")
5
+ canvas.height = height
6
+ canvas.width = width
7
+ canvas.style.scale = scale
8
+ if(flipYAxis){
9
+ canvas.getContext("2d").translate(0, canvas.height)
10
+ canvas.getContext("2d").scale(1, -1)
11
+ }
12
+ const parentElement = parent ?? document.querySelector("body")
13
+ parentElement.insertAdjacentElement("beforeend", canvas)
14
+ return {
15
+ element: canvas,
16
+ ctx: canvas.getContext("2d")
17
+ }
18
+ }
19
+ export class Render {
20
+ //Chỉnh toạ độ thì sửa toạ độ này, tránh tạo nhiều object
21
+ #lastTimestamp = 0
22
+ #isPlaying = false
23
+ #entities = []
24
+ #isRendered = false
25
+ #backgroundColor = "white"
26
+ #updateFunctions = []
27
+ #dt = 0
28
+ constructor(canvas){
29
+ this.ctx = canvas.getContext("2d")
30
+ this.canvas = canvas
31
+ this.currentId = 0
32
+ }
33
+ getEntities(){
34
+ return [...this.#entities]
35
+ }
36
+ addEntities(...entities){
37
+ for(let e of entities){
38
+ this.#entities.push(e)
39
+ // e.setId(this.currentId)
40
+ // this.currentId += 1
41
+ }
42
+ }
43
+ removeEntities(...entities){
44
+ for(let e of entities){
45
+ const index = this.#entities.indexOf(e)
46
+ if(index !== -1){
47
+ this.#entities.splice(index,1)
48
+ }
49
+ }
50
+ }
51
+ copy(){
52
+ return this
53
+ }
54
+ render(){
55
+ this.clear()
56
+ this.paintBackgroundColor()
57
+ for(let e of this.#entities){
58
+ try{
59
+ e.draw(this.ctx)
60
+ } catch(error){
61
+ console.error("Can not render this entity",e,"==========\n",error)
62
+ this.#isRendered = false
63
+ return
64
+ }
65
+ }
66
+ this.#isRendered = true
67
+ }
68
+ play(){
69
+ if(this.#isRendered && !this.#isPlaying){
70
+ this.#isPlaying = true
71
+ requestAnimationFrame(this.#loop.bind(this))
72
+ } else{
73
+ console.error("You must render first")
74
+ }
75
+ this.#lastTimestamp = null
76
+ }
77
+ pause(){
78
+ if(this.#isRendered){
79
+ this.#isPlaying = false
80
+ } else{
81
+ console.error("You must render first")
82
+ }
83
+ }
84
+ #loop(timestamp){
85
+ timestamp = timestamp ?? 0
86
+ this.#dt = this.#lastTimestamp === null ? 0 : (timestamp - this.#lastTimestamp)/1000
87
+ this.#lastTimestamp = timestamp
88
+ if(this.#isPlaying){
89
+ for(let func of this.#updateFunctions){
90
+ if(func.isEnabled){
91
+ try{
92
+ func(this.#dt)
93
+ } catch(e){
94
+ console.error("There is something wrong with updateFunction.\n", e)
95
+ this.pause()
96
+ }
97
+ }
98
+ }
99
+ this.render()
100
+ requestAnimationFrame(this.#loop.bind(this))
101
+ }
102
+ }
103
+ clear(){
104
+ this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)
105
+ }
106
+ setBackgroundColor(color){
107
+ this.#backgroundColor = color
108
+ }
109
+ paintBackgroundColor(){
110
+ this.ctx.fillStyle = this.#backgroundColor
111
+ this.ctx.fillRect(
112
+ 0,0,
113
+ this.canvas.width, this.canvas.height
114
+ )
115
+ }
116
+ addUpdater(updateFunction){
117
+ if(typeof updateFunction == "function"){
118
+ this.#updateFunctions.push(updateFunction)
119
+ updateFunction.isEnabled = true
120
+ } else{
121
+ console.error("updateFunction must be a function")
122
+ }
123
+ }
124
+ removeUpdater(updateFunction){
125
+ const index = this.#updateFunctions.indexOf(updateFunction)
126
+ if(index !== -1){
127
+ this.#updateFunctions.splice(index,1)
128
+ }else{
129
+ console.warn("updateFunction not found:", updateFunction)
130
+ }
131
+ }
132
+ disableUpdater(updateFunction){
133
+ if(typeof updateFunction == "function"){
134
+ updateFunction.isEnabled = false
135
+ } else{
136
+ console.error("updateFunction must be a function")
137
+ }
138
+ }
139
+ enableUpdater(updateFunction){
140
+ if(typeof updateFunction == "function"){
141
+ updateFunction.isEnabled = true
142
+ } else{
143
+ console.error("updateFunction must be a function")
144
+ }
145
+ }
146
+ async wait(ms){
147
+ return new Promise((resolve)=>{
148
+ setTimeout(resolve, ms)
149
+ })
150
+ }
151
+ //Công thức chung: [giá trị đầu] + [biến thiên]*[tiến độ]
152
+ #changeProperties(calcFunc, duration = 1, timingFunc = animation.LINEAR){
153
+ if(duration>0 && Number.isFinite(duration)){
154
+ return new Promise(resolve => {
155
+ let elapsed = 0
156
+ const updater = (dt)=>{
157
+ elapsed += dt
158
+ let progress = Math.min(elapsed/duration, 1)
159
+ let easedProgress = timingFunction(progress, timingFunc)
160
+ calcFunc(easedProgress)
161
+ if(progress>=1){
162
+ this.removeUpdater(updater)
163
+ resolve()
164
+ }
165
+ }
166
+ this.addUpdater(updater)
167
+ })
168
+ } else{
169
+ console.error("Duration must be a finite number and greater than 0")
170
+ }
171
+ }
172
+ // TODO: nhớ kiểm tra lại xem có tạo Object mới không cần thiết không
173
+ async moveTo(entity, coords2, duration = 1, timingFunc = animation.EASE_IN_OUT){
174
+ const startPos = entity.getCoordinates2()
175
+ await this.#changeProperties((easedProgress)=>{
176
+ entity.setCoordinates2(startPos.shift(coords2.subtract(startPos).multiply(easedProgress)))
177
+ }, duration, timingFunc)
178
+ }
179
+ async shift(entity, vector2, duration = 1, timingFunc = animation.EASE_IN_OUT){
180
+ await this.moveTo(entity, entity.getCoordinates().shift(vector2), duration, timingFunc)
181
+ }
182
+ async setScale(entity, scale, duration = 1, timingFunc = animation.EASE_IN_OUT){
183
+ const startScale = entity.getScale()
184
+ await this.#changeProperties((easedProgress)=>{
185
+ entity.scale(startScale + (scale - startScale)*easedProgress)
186
+ }, duration, timingFunc)
187
+ }
188
+ async rotate(entity, rad, duration = 1, timingFunc = animation.EASE_IN_OUT){
189
+ const startAngle = entity.getRotationAngle()
190
+ await this.#changeProperties((easedProgress)=>{
191
+ entity.rotate(startAngle + (rad - startAngle)*easedProgress)
192
+ }, duration, timingFunc)
193
+ }
194
+ async transform(entity, matrix, duration = 1, timingFunc = animation.EASE_IN_OUT){
195
+ let m = new Matrix([[0,0],[0,0]])
196
+ const entityMatrix = entity.getCustomMatrix()
197
+ await this.#changeProperties((easedProgress)=>{
198
+ for(let r = 0; r < entityMatrix.getMatrix().length; r++){
199
+ for(let c = 0; c < entityMatrix.getMatrix()[r].length; c++){
200
+ const cellValue = entityMatrix.getMatrix()[r][c]
201
+ m.changeValue(r,c, cellValue + (matrix.getMatrix()[r][c] - cellValue)*easedProgress)
202
+ }
203
+ }
204
+ entity.transform(m)
205
+ }, duration, timingFunc)
206
+ }
207
+ async setStartAndEndPoint(entity, start, end, duration = 1, timingFunc){
208
+ if(entity.constructor.name === "Line" || entity.constructor.name === "Arrow"){
209
+ const start0 = entity.getStartPoint()
210
+ const end0 = entity.getEndPoint()
211
+ const coords1 = new Coordinates2()
212
+ const coords2 = new Coordinates2()
213
+ await this.#changeProperties((easedProgress)=>{
214
+ coords1.setCoordinates2(
215
+ start0.x + (start.x - start0.x)*easedProgress,
216
+ start0.y + (start.y - start0.y)*easedProgress
217
+ )
218
+ coords2.setCoordinates2(
219
+ end0.x + (end.x - end0.x)*easedProgress,
220
+ end0.y + (end.y - end0.y)*easedProgress
221
+ )
222
+ entity.setStartAndEndPoint(coords1,coords2)
223
+ }, duration, timingFunc)
224
+ }
225
+ }
226
+ }
package/src/shapes.js ADDED
@@ -0,0 +1,368 @@
1
+ import * as constants from "./constants.js"
2
+ import { Coordinates2, Matrix, Vector2 } from "./math.js"
3
+ /*
4
+ Trong trường hợp bản thân đọc lại code và đếch hiểu gì:
5
+ - Các class thuộc đoạn thẳng, đa giác đều có các điểm được xác định bởi các vector.
6
+ - Xoay, thu phóng đều được thực hiện thông qua việc nhân ma trận với vector
7
+ - Render chỉ render các vector được biến đổi, giá trị vector gốc được giữ lại
8
+ */
9
+ // TODO: quay mũi tên!
10
+ const rotationMatrix = new Matrix([[],[]])
11
+ function getRotationMatrix(angle){
12
+ rotationMatrix.setMatrix([
13
+ [Math.cos(angle), - Math.sin(angle)],
14
+ [Math.sin(angle), Math.cos(angle)]
15
+ ])
16
+ return rotationMatrix
17
+ }
18
+ class Entity {
19
+ #rotationAngle
20
+ #scale = 1
21
+ constructor(properties = {}){
22
+ this.x = properties.x ?? 0
23
+ this.y = properties.y ?? 0
24
+ this.entityName = properties.entityName ?? "TinieEntity"
25
+ this.id = -1
26
+ this.#rotationAngle = 0
27
+ }
28
+ getCoordinates(){
29
+ return new Coordinates2(this.x, this.y)
30
+ }
31
+ scale(k){
32
+ if (Number.isFinite(k)){
33
+ this.#scale = k
34
+ this.updateVectors()
35
+ } else{
36
+ console.log("Scale must be a finite number", k);
37
+ }
38
+ }
39
+ getScale(){
40
+ return this.#scale
41
+ }
42
+ getRotationAngle(){
43
+ return this.#rotationAngle
44
+ }
45
+ rotate(rad){
46
+ if(typeof rad === 'number' && Number.isFinite(rad)){
47
+ this.#rotationAngle = rad
48
+ this.updateVectors()
49
+ }else{
50
+ console.error("Angle of rotation must be a number")
51
+ }
52
+ }
53
+ updateVectors(rad){
54
+
55
+ }
56
+ getCoordinates2(){
57
+ return new Coordinates2(this.x, this.y)
58
+ }
59
+ setCoordinates2(coords2){
60
+ this.x = coords2.x
61
+ this.y = coords2.y
62
+ }
63
+ shift(vector2){
64
+ this.x += vector2.x
65
+ this.y += vector2.y
66
+ }
67
+ draw(){
68
+ console.error("This Entity does not have draw function")
69
+ }
70
+ setId(id){
71
+ if(typeof(id) == "number"){
72
+ if(id >=-1){
73
+ this.id = id
74
+ } else{
75
+ console.error("Id must be greater than or equal to -1")
76
+ }
77
+ } else{
78
+ console.error("Id must be a number")
79
+ }
80
+ }
81
+ }
82
+ class Shape extends Entity{
83
+ #vectors = []
84
+ #scaleMatrix
85
+ #customMatrix = new Matrix([[1,0],[0,1]])
86
+ #originalVectors
87
+ constructor(properties = {}){
88
+ super(properties)
89
+ this.color = properties.color ?? constants.COLORS.Blue
90
+ this.strokeColor = properties.strokeColor ?? null
91
+ this.strokeWidth = properties.strokeWidth ?? 2
92
+ this.#scaleMatrix = new Matrix([[this.getScale(),0],[0,this.getScale()]])
93
+ }
94
+ getCustomMatrix(){
95
+ return this.#customMatrix
96
+ }
97
+ setOriginalVectors(vectorsArray){
98
+ this.#originalVectors = vectorsArray
99
+ }
100
+ getOriginalVectors(){
101
+ return this.#originalVectors
102
+ }
103
+ getVectors(){
104
+ return this.#vectors
105
+ }
106
+ setVectors(vectorsArray){
107
+ this.#vectors = vectorsArray
108
+ }
109
+ resetVectors(){
110
+ this.#vectors = this.#originalVectors
111
+ }
112
+ updateVectors(){
113
+ this.#scaleMatrix.setMatrix([[this.getScale(),0],[0,this.getScale()]])
114
+ const ogVectorLength = this.#originalVectors.length
115
+ if(this.#vectors.length < ogVectorLength){
116
+ this.#vectors = []
117
+ for(let i = 0; i < ogVectorLength; i++){
118
+ this.#vectors.push(new Vector2(0,0))
119
+ }
120
+ }
121
+ const matrix = getRotationMatrix(this.getRotationAngle()).multiply(this.#customMatrix.multiply(this.#scaleMatrix))
122
+ for(let i = 0; i < this.#vectors.length; i++){
123
+ let vector = this.#originalVectors[i].toMatrix()
124
+ vector = matrix.multiply(vector)
125
+ vector = new Vector2(vector.getMatrix()[0][0], vector.getMatrix()[1][0])
126
+ this.#vectors[i] = vector
127
+ }
128
+ }
129
+ transform(matrix){
130
+ if(matrix.isValid() && matrix.getMatrix().length == 2){
131
+ this.#customMatrix = matrix
132
+ this.updateVectors()
133
+ } else{
134
+ console.error("Matrix is invalid", matrix)
135
+ }
136
+ }
137
+ }
138
+ // Tôi đéo biết tại sao Group lại kế thừa từ Shape
139
+ export class Group{
140
+ #vector
141
+ #entities
142
+ constructor(...entities){
143
+ this.#entities = entities
144
+ this.coordsArray = []
145
+ this.updateCoordsArray(this.#entities)
146
+ }
147
+ getEntities(){
148
+ return this.#entities
149
+ }
150
+ addEntities(...entities){
151
+ for(const entity of entities){
152
+ this.#entities.push(entity)
153
+ }
154
+ this.updateCoordsArray(this.#entities)
155
+ }
156
+ updateCoordsArray(...entities){
157
+ for(const entity of entities){
158
+ if(entity.x !== null && entity.y !== null){
159
+ this.coordsArray.push(new Coordinates2(entity.x, entity.y))
160
+ }
161
+ }
162
+ }
163
+ async applyFunction(func){
164
+ for(const entity of this.#entities){
165
+ func(entity)
166
+ }
167
+ }
168
+ shift(vector){
169
+ if(vector.constructor.name == "Vector2"){
170
+ for(const entity of this.#entities){
171
+ entity.shift(vector)
172
+ }
173
+ } else{
174
+ throw TypeError("'vector' must be a vector", vector)
175
+ }
176
+ }
177
+ draw(ctx){
178
+ for(const entity of this.#entities){
179
+ entity.draw(ctx)
180
+ }
181
+ }
182
+ }
183
+ export class Line extends Shape{
184
+ #start
185
+ #end
186
+ constructor(properties = {}){
187
+ super(properties)
188
+ this.#start = properties.start ?? new Coordinates2(0,0)
189
+ this.#end = properties.end ?? new Coordinates2(10,10)
190
+ this.color = null
191
+ this.strokeColor = properties.color ?? constants.COLORS.Yellow
192
+ this.setOriginalVectors([
193
+ this.#end.subtract(this.#start)
194
+ ])
195
+ this.updateVectors()
196
+ }
197
+ getAngle(){
198
+ return Math.atan2(this.getVectors()[0].y, this.getVectors()[0].x)
199
+ }
200
+ getStartPoint(){
201
+ return this.#start
202
+ }
203
+ getEndPoint(){
204
+ return this.#end
205
+ }
206
+ setStartAndEndPoint(start, end){
207
+ this.#start = start
208
+ this.#end = end
209
+ this.setOriginalVectors([
210
+ this.#end.subtract(this.#start)
211
+ ])
212
+ this.updateVectors()
213
+ }
214
+ draw(ctx){
215
+ ctx.beginPath();
216
+ if(this.strokeColor !== null){
217
+ ctx.strokeStyle = this.strokeColor;
218
+ }
219
+ ctx.lineWidth = this.strokeWidth;
220
+ ctx.moveTo(this.#start.x, this.#start.y);
221
+ ctx.lineTo(this.getVectors()[0].x + this.#start.x, this.getVectors()[0].y + this.#start.y);
222
+ ctx.stroke()
223
+ }
224
+ }
225
+ export class Arrow extends Line{
226
+ #arrowTipVector
227
+ #renderedArrowTipVector
228
+ constructor(properties = {}){
229
+ super(properties)
230
+ this.arrowTipScale = properties.arrowTipScale ?? 1
231
+ this.setOriginalVectors([
232
+ this.getEndPoint().subtract(this.getStartPoint()),
233
+ ])
234
+ this.updateVectors()
235
+ this.#arrowTipVector = [
236
+ new Vector2(-5*this.arrowTipScale, -5*this.arrowTipScale),
237
+ new Vector2(-5*this.arrowTipScale, 5*this.arrowTipScale)
238
+ ]
239
+ this.#renderedArrowTipVector = [
240
+ new Vector2(-5*this.arrowTipScale, -5*this.arrowTipScale),
241
+ new Vector2(-5*this.arrowTipScale, 5*this.arrowTipScale)
242
+ ]
243
+ }
244
+ draw(ctx){
245
+ ctx.beginPath();
246
+ if(this.strokeColor !== null){
247
+ ctx.strokeStyle = this.strokeColor;
248
+ }
249
+ ctx.lineWidth = this.strokeWidth;
250
+ const end = {
251
+ x: this.getVectors()[0].x + this.getStartPoint().x,
252
+ y: this.getVectors()[0].y + this.getStartPoint().y
253
+ }
254
+ ctx.moveTo(this.getStartPoint().x, this.getStartPoint().y);
255
+ ctx.lineTo(end.x, end.y);
256
+ ctx.stroke()
257
+ if(this.getVectors()[0].getLength() !== 0){
258
+ this.drawTip(ctx, end)
259
+ }
260
+ }
261
+ drawTip(ctx, end){
262
+ // Arrow tip
263
+ this.rotateArrowTip(this.getAngle())
264
+ ctx.moveTo(end.x, end.y)
265
+ ctx.lineTo(end.x + this.#renderedArrowTipVector[0].x, end.y + this.#renderedArrowTipVector[0].y)
266
+ ctx.moveTo(end.x, end.y)
267
+ ctx.lineTo(end.x + this.#renderedArrowTipVector[1].x, end.y + this.#renderedArrowTipVector[1].y)
268
+ ctx.stroke()
269
+ }
270
+ rotateArrowTip(rad){
271
+ for(let i = 0; i < this.#renderedArrowTipVector.length; i ++){
272
+ let vector = getRotationMatrix(rad).multiply(this.#arrowTipVector[i].toMatrix())
273
+ this.#renderedArrowTipVector[i].setVector(vector.getMatrix()[0][0], vector.getMatrix()[1][0])
274
+ }
275
+ }
276
+ }
277
+ export class Rectangle extends Shape{
278
+ constructor(properties = {}){
279
+ super(properties)
280
+ this.width = properties.width ?? 50
281
+ this.height = properties.height ?? 50
282
+ const vectors = [
283
+ new Vector2(-this.width/2, -this.height/2),
284
+ new Vector2(this.width/2, -this.height/2),
285
+ new Vector2(this.width/2, this.height/2),
286
+ new Vector2(-this.width/2, this.height/2)
287
+ ]
288
+ this.setOriginalVectors(vectors.map(v => new Vector2(v.x, v.y)))
289
+ this.updateVectors()
290
+ }
291
+ resize(width, height){
292
+ this.width = width
293
+ this.height = height
294
+ this.updateVectors()
295
+ }
296
+ draw(ctx){
297
+ try{
298
+ ctx.beginPath()
299
+ ctx.lineWidth = this.strokeWidth;
300
+ const vectors = this.getVectors()
301
+ ctx.moveTo(vectors[0].x + this.x, vectors[0].y + this.y)
302
+ ctx.lineTo(vectors[1].x + this.x, vectors[1].y + this.y)
303
+ ctx.lineTo(vectors[2].x + this.x, vectors[2].y + this.y)
304
+ ctx.lineTo(vectors[3].x + this.x, vectors[3].y + this.y)
305
+ ctx.lineTo(vectors[0].x + this.x, vectors[0].y + this.y - this.strokeWidth/2)
306
+ if(this.color !== null){
307
+ ctx.fillStyle = this.color
308
+ ctx.fill()
309
+ }
310
+ ctx.closePath()
311
+ if(this.strokeColor !== null){
312
+ ctx.strokeStyle = this.strokeColor;
313
+ ctx.stroke()
314
+ }
315
+ }catch(e){
316
+ console.error("Can not draw this Entity\n", e)
317
+ }
318
+ }
319
+ }
320
+ export class Arc extends Shape{
321
+ #renderRadius
322
+ #scale = 1
323
+ constructor(properties = {}){
324
+ super(properties)
325
+ this.radius = properties.radius ?? 25
326
+ this.startAngle = properties.startAngle ?? 0
327
+ this.endAngle = properties.endAngle ?? Math.PI/2
328
+ this.strokeColor = properties.strokeColor ?? constants.COLORS.Blue
329
+ this.color = properties.color ?? null
330
+ this.scale(1)
331
+ }
332
+ resize(radius){
333
+ this.radius = radius
334
+ }
335
+ scale(k){
336
+ this.#renderRadius = k*this.radius
337
+ this.#scale = k
338
+ }
339
+ getScale(){
340
+ return this.#scale
341
+ }
342
+ draw(ctx){
343
+ try{
344
+ ctx.beginPath()
345
+ ctx.arc(this.x, this.y, this.#renderRadius*this.getScale(), this.startAngle, this.endAngle)
346
+ if(this.color !== null){
347
+ ctx.fillStyle = this.color
348
+ ctx.fill()
349
+ }
350
+ ctx.lineWidth = this.strokeWidth;
351
+ if(this.strokeColor !== null){
352
+ ctx.strokeStyle = this.strokeColor
353
+ ctx.stroke()
354
+ }
355
+ }catch(e){
356
+ console.error("Can not draw this Entity");
357
+ }
358
+ }
359
+ }
360
+ export class Circle extends Arc{
361
+ constructor(properties = {}){
362
+ super(properties)
363
+ this.startAngle = 0
364
+ this.endAngle = Math.PI*2
365
+ this.color = properties.color ?? constants.COLORS.Blue
366
+ this.strokeColor = properties.strokeColor ?? null
367
+ }
368
+ }
@@ -0,0 +1,11 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ </head>
7
+ <body style="background-color: rgb(32, 33, 35);">
8
+
9
+ </body>
10
+ <script type="module" src="./index.js"></script>
11
+ </html>
package/test/index.js ADDED
@@ -0,0 +1,46 @@
1
+ //Code by TKien2
2
+ import * as TinieAnim from "../index.js"
3
+ const canvas = TinieAnim.createScreen(500,400)
4
+ const renderer = new TinieAnim.Render(canvas.element)
5
+ const center = new TinieAnim.Coordinates2(200,200)
6
+ const rect = new TinieAnim.Rectangle({
7
+ x: center.x, y: center.y,
8
+ width: 100, height: 50,
9
+ color: TinieAnim.COLORS.Red
10
+ })
11
+ const a1 = new TinieAnim.Arrow({
12
+ start: center,
13
+ end: center.shift(new TinieAnim.Vector2(50,25))
14
+ })
15
+ const a2 = new TinieAnim.Arrow({
16
+ start: center,
17
+ end: center.shift(new TinieAnim.Vector2(-50,25))
18
+ })
19
+ const a3 = new TinieAnim.Arrow({
20
+ start: center,
21
+ end: center.shift(new TinieAnim.Vector2(50,-25))
22
+ })
23
+ const a4 = new TinieAnim.Arrow({
24
+ start: center,
25
+ end: center.shift(new TinieAnim.Vector2(-50,-25))
26
+ })
27
+ const gr = new TinieAnim.Group(rect, a1, a2, a3, a4)
28
+ const m = new TinieAnim.Matrix([
29
+ [1,1.3],
30
+ [0.7,2]
31
+ ])
32
+ const m1 = new TinieAnim.Matrix([
33
+ [1.4,0.3],
34
+ [2.2,1.5]
35
+ ])
36
+ renderer.setBackgroundColor(TinieAnim.COLORS.Void)
37
+ renderer.addEntities(gr)
38
+ renderer.render()
39
+ renderer.play()
40
+ gr.applyFunction((entity)=>{
41
+ renderer.transform(entity,m)
42
+ })
43
+ await renderer.wait(1000)
44
+ gr.applyFunction((entity)=>{
45
+ renderer.transform(entity, m1)
46
+ })