Skip to content

Commit

Permalink
Add function to rotate sprite images
Browse files Browse the repository at this point in the history
  • Loading branch information
AntumDeluge committed Dec 4, 2023
1 parent 95df852 commit 9d0d50a
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
4 changes: 4 additions & 0 deletions srcjs/stendhal.css
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,10 @@ div.logcolR {
margin: 2px;
}

canvas#drawing-stage {
display: none;
}

@font-face {
font-family: Amaranth;
src: url("/data/font/Amaranth-Regular.ttf");
Expand Down
3 changes: 3 additions & 0 deletions srcjs/stendhal.html
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,9 @@ <h3></h3>
<div></div>
</template>

<!-- hidden canvas for manipulating images before being displayed -->
<canvas id="drawing-stage"></canvas>

<script type="text/javascript" src="stendhal-compiled.js"></script>
</body>

Expand Down
55 changes: 55 additions & 0 deletions srcjs/stendhal/data/SpriteStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,61 @@ export class SpriteStore {
});
}

/**
* Rotates an image.
*
* @param img
* Image to be rotated.
* @param angle
* Angle of rotation.
*/
private rotate(img: HTMLImageElement, angle: number) {
const canvas = <HTMLCanvasElement> document.getElementById("drawing-stage")!;
const ctx = canvas.getContext("2d")!;
// make sure working with blank canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = img.width;
canvas.height = img.height;

ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(angle * Math.PI / 180);
ctx.translate(-canvas.width / 2, -canvas.height / 2);
ctx.drawImage(img, 0, 0);

img.src = canvas.toDataURL("image/png");
}

/**
* Retrieves a rotated image.
*
* @param filename
* Path to target image file.
* @param angle
* Angle of rotation.
* @return
* HTMLImageElement.
*/
getRotated(filename: string, angle: number): any {
if (angle == 0) {
return this.get(filename);
}
const id = filename + "-rot" + angle;
if (this.images[id]) {
return this.images[id];
}
const img = this.get(filename).cloneNode();
if (img.complete) {
this.rotate(img, angle);
} else {
img.onload = () => {
this.rotate(img, angle);
img.onload = undefined;
}
}
this.images[id] = img;
return img;
}

/**
* Used when we only want an image if it was previously cached.
*
Expand Down

0 comments on commit 9d0d50a

Please sign in to comment.