'Angular how to manage multiple canvas elements for images
I have a page with many images. the ngFor worked ok for image tags
But I want canvas(es)
I do not know how to manage "id" and getElementById , in a dynamic environment
Eg:
I can update <canvas id="tools_sketch" style="border:1px solid #000000;">
to
<canvas id="tools_sketch{{q}}" style="border:1px solid #000000;">
But how to update
const canvas = <HTMLCanvasElement> document.getElementById('tools_sketch??');
Please see the stackblitz https://stackblitz.com/edit/angular-ivy-fk9hbp?file=src/app/app.component.html
How can I locate the element (or ) alternate solution please (how is image tag working? and not canvas ?)
Solution 1:[1]
One possible way is to bind to [id] attribute.
<div *ngFor="let q of [0, 1]">
[{{ q }}]
<img id="myimage" [src]="getImage(q)" />
<canvas [id]="'tools_sketch_' + q" style="border:1px solid #000000;">
using the q variable: [id]="'tools_sketch_' + q"
Then you can use it TS with something like:
draw() {
this.drawOnCanvas(0);
this.drawOnCanvas(1);
}
private drawOnCanvas(canvasId: number) {
const canvas = <HTMLCanvasElement>(
document.getElementById('tools_sketch_' + canvasId) // <-- id
);
if (!canvas) {
return;
}
const ctx = canvas.getContext('2d');
ctx.drawImage(<HTMLCanvasElement>document.getElementById('myimage'), 0, 0);
}
Working Stackblitz
UPDATE
To display different images on 1st and 2nd canvas
load images and when all the images are loaded call the draw method:
ngOnInit(): void {
this.imageArray.forEach((q) => {
const image = new Image();
image.src = 'data:image/png;base64,' + q;
image.onload = () => {
console.log('onload');
++this.loadedImageCounter;
if (this.imageArray.length == this.loadedImageCounter) {
this.draw();
}
};
this.images.push(image);
});
}
all images are stored in a separate array and a callback onload is registered to get notification when an image is ready when all is ready - loaded. then issue a draw call. Beside canvasId and imageId is also provided.
draw() {
console.log('draw');
this.drawOnCanvas(0, 0);
this.drawOnCanvas(1, 1);
}
private drawOnCanvas(canvasId: number, imageId: number) {
const canvas = <HTMLCanvasElement>(
document.getElementById('tools_sketch_' + canvasId)
);
if (!canvas) {
return;
}
const ctx = canvas.getContext('2d');
ctx.drawImage(this.images[imageId], 0, 0);
}
Working Stackblitz
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
