Skip to content

Commit

Permalink
Merge pull request #11 from devshareacademy/GH-45/canvas-api-image-ex…
Browse files Browse the repository at this point in the history
…ample

[GH-45] canvas api image example
  • Loading branch information
scottwestover authored Sep 7, 2023
2 parents 3a5d67b + 056763e commit 1ccbfd1
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
2 changes: 1 addition & 1 deletion canavs-api/basic-image-example/.vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"prettier.singleQuote": true,
"prettier.semi": true,
"editor.formatOnSave": true,
"cSpell.words": []
"cSpell.words": ["tileset"]
}
2 changes: 2 additions & 0 deletions canavs-api/basic-image-example/src/encoded-image.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

52 changes: 51 additions & 1 deletion canavs-api/basic-image-example/src/main.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,40 @@
import { encodedImage } from './encoded-image.js';

/**
* @param {string} src
* @returns {Promise<HTMLImageElement>}
*/
function loadImage(src) {
return new Promise((resolve) => {
const img = new Image();
img.addEventListener(
'load',
() => {
resolve(img);
},
false
);
img.src = src;
});
}

/**
* @returns {Promise<HTMLImageElement>}
*/
function getEncodedImage() {
return new Promise((resolve) => {
const img = new Image();
img.addEventListener(
'load',
() => {
resolve(img);
},
false
);
img.src = encodedImage;
});
}

void (async function () {
const canvas = document.getElementById('game');
if (!(canvas instanceof HTMLCanvasElement)) {
Expand All @@ -10,5 +47,18 @@ void (async function () {
return;
}

// TODO: add main logic
const img = await loadImage('assets/grunge-tileset.png');
// const img = await getEncodedImage();

// example of drawing image directly
// drawImage(image, dx, dy)
ctx.drawImage(img, 0, 0);

// example of scaling by providing width and height on destination
// drawImage(image, dx, dy, dWidth, dHeight)
// ctx.drawImage(img, 0, 0, img.width * 1.5, img.height * 1.5);

// example of slicing image by providing the source image values and destination canvas details
// drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
// ctx.drawImage(img, 200, 0, 200, 160, 100, 0, 200, 160);
})();

0 comments on commit 1ccbfd1

Please sign in to comment.