Reputation: 597
I have an image i am getting from a url. I would like to draw a rectangle on this image. I'm currently trying to use canvas to achieve this but i'm not fully understanding how to implement it. When i use this code there is no change in the canvas, it remains blank.
I have this in my html
<canvas #layout></canvas>
Then this in my component typescript file
@ViewChild('layout') canvasRef;
//other code here
drawRectangle(file: any): void
{
let canvas = this.canvasRef.nativeElement;
let context = canvas.getContext('2d');
let source = new Image();
source.src = this.imgUrl;
source.onload = () =>
{
context.drawImage(source.src,0,0);
context.beginPath();
context.rect(file.left, file.top, file.width, file.height);
context.stroke();
};
}
Upvotes: 1
Views: 8563
Reputation: 8078
try adding the onload()
callback after the updating the source.src
. also you need to pass the image (source
) to drawImage
not source.src
so here is the updated code:
so
@ViewChild('layout') canvasRef;
//other code here
drawRectangle(file: any): void
{
let canvas = this.canvasRef.nativeElement;
let context = canvas.getContext('2d');
let source = new Image();
source.onload = () =>
{
context.drawImage(source, 0, 0);
context.beginPath();
context.rect(file.left, file.top, file.width, file.height);
context.stroke();
};
source.src = this.imgUrl;
}
Upvotes: 2