Skip to content

Instantly share code, notes, and snippets.

@theAlgorithmist
Created August 11, 2021 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theAlgorithmist/a87b3ab9ebf483d20f7bd609ac23ab12 to your computer and use it in GitHub Desktop.
Save theAlgorithmist/a87b3ab9ebf483d20f7bd609ac23ab12 to your computer and use it in GitHub Desktop.
public setPreviewImage(imgURL: string): void
{
if (this._canvas !== undefined)
{
const img: HTMLImageElement = new Image();
this._url = imgURL;
img.crossOrigin = 'anonymous';
// TODO This only works for a single image load. As an exercise, modify to handle deletion (including handlers)
// and re-initializing of a new Image if the setPreviewImage() method is called multiple times
img.onload = () =>
{
// which dimension is binding?
const w: number = img.width as number;
const h: number = img.height as number;
const s1: number = w / this._canvas.width;
const s2: number = h / this._canvas.height;
const ctx: CanvasRenderingContext2D = this._canvas.getContext('2d') as CanvasRenderingContext2D;
let d: number;
let left: number = 0;
let top: number = 0;
let right: number = 0;
let bottom: number = 0;
if (s1 >= s2)
{
d = this._canvas.height - (h/s1);
left = 0;
top = Math.round(0.5*d);
right = this._canvas.width;
bottom = h / s1;
}
else
{
d = this._canvas.width - (w/s2);
left = Math.round(0.5*d);
top = 0;
right = w / s2;
bottom = this._canvas.height;
}
ctx.drawImage(img, left, top, right, bottom);
const data: Uint8ClampedArray = this._canvas.getContext("2d")!.getImageData(left, top, right, bottom).data;
const n: number = data.length;
let i: number;
// process rgb and skip over alpha
for (i = 0; i < n; i+=4) {
this._rgbArr.push( {r: data[i], g: data[i+1], b: data[i+2]} );
}
this._onLoaded.emit(this._url);
};
img.onerror = () => this._onImgError.emit(this._url);
img.style.display = 'none';
img.src = imgURL;
}
}
@ezzabuzaid
Copy link

ezzabuzaid commented Sep 1, 2021

Hi!
You can set the extension of the file to give it code highlights and to make it more readable.
instead of "setPreviewImage" use "setPreviewImage.ts".

Helpful Article! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment