0

I am trying to compress image from client side, but getting error at line cvs = ctx.drawImage(file, 0, 0, 100, 100);

But getting black image of 1 kb, need help

selectImage(event: any){
if(event.target.files.length>0){  
    const file = event.target.files[0];
    this.reader_img(file);
 }
}
reader_img(file:File){
let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      if(!(reader.result)){
        throw new Error(`error1`)
      }
      var img1 = new Image(); 
      img1.src = reader.result.toString();
      var cvs = document.createElement('canvas');
      var ctx=cvs.getContext("2d");
      if (!(ctx)) {
        throw new Error(` error2`);
      }
      ctx.drawImage(img1, 400, 400);
      console.log(cvs.toDataURL());
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    };
}
vignesh p
  • 1
  • 1
  • You're declaring `ctx`, but not assigning anything to the variable. Therefore, it is *undefined*. – R. Richards Oct 15 '21 at 12:53
  • Does this answer your question? [CanvasContext2D drawImage() issue \[onload and CORS\]](https://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue-onload-and-cors) – Kaiido Oct 21 '21 at 02:32

1 Answers1

0

Your ctx object is unassigned, because you didn´t assign anything in the line above (let ctx: any;). Also drawImage returns void. The image is drawn to the canvas that the CanvasRenderingContext2D is bound to. Try this instead:

var cvs = document.createElement('canvas');
let ctx = cvs.getContext("2d");
ctx.drawImage(file, 0, 0, 100, 100);
JonasK
  • 149
  • 2
  • 8