-1

I am new to JavaScript. Last few days I make extension for Chrome, which takes screenshots of all tabs and pushes this data to clipboard. Each image weighs a lot and so I decided to compress them. But it doesn't work. Can anyone know what the problem is?

function copyToClipBoard(dataImage){
    document.body.appendChild(input);
    input.style.position = 'fixed';
    input.style.opacity = 0;

    var newImage = new Image();
    newImage.src = dataImage;
    console.log (newImage); 

    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext("2d").drawImage(newImage, 0, 0);
    input.value = canvas.toDataURL('image/jpeg', 0.1);
    console.log(input.value);
    input.select();
    document.execCommand('Copy');
    document.body.removeChild(input);
}
Sergey
  • 1
  • 4
  • 3
    I don't see any code that actually does any compression… What do you mean by “it doesn't work”? What error messages are you getting? – Patrick Hund Apr 21 '17 at 08:26
  • When i am debugging this code, In the console I get a link to the image that is displayed as a black box. This line is compress input.value = canvas.toDataURL('image/jpeg', 0.1); – Sergey Apr 21 '17 at 08:30
  • You are not waiting for your image has loaded before drawing it on your canvas. `newImage.onload = function(){ var canvas ...removeChild(input)};`+ you'll need `canvas.width = img.width; canvas.height= img.height;` – Kaiido Apr 21 '17 at 09:11
  • Possible duplicate of [CanvasContext2D drawImage() issue \[onload and CORS\]](http://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue-onload-and-cors) – Kaiido Apr 21 '17 at 09:20

1 Answers1

0

Thank, Kaiido. Now everythink works. The problem was that the picture did not have time to load before drawing.

function copyToClipBoard(dataImage){
    document.body.appendChild(input);
    input.style.position = 'fixed';
    input.style.opacity = 0;

    var newImage = new Image();
    newImage.src = dataImage;
    console.log (newImage); 

    newImage.onload = function(){
       var canvas = document.createElement('canvas');
       canvas.width = 800;
       canvas.height = 500;
       var ctx = canvas.getContext("2d").drawImage(newImage, 0, 0, newImage.width, newImage.height, 0, 0, canvas.width, canvas.height);
       input.value = canvas.toDataURL('image/jpeg', 0.9);
       console.log(input.value);
       input.select();
       document.execCommand('Copy');
       document.body.removeChild(input);
    }
}
Sergey
  • 1
  • 4