1

I am expecting to return image Mirror-ed and it returns black image.

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      margin: 0px;
      padding: 0px;
    }
  </style>
</head>

<body>
  <img id="canvasImg" alt="Right click to save me!">
  <!--PLACE WHERE IMAGE MUST BE PUT ANFTER MIRROR-->
  <canvas id="myCanvas" width="1000" height="1000" style="background:#0094ff"></canvas>
  <!--Canvas Element-->
  <script>
    /*Creating Canvas*/
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

     // translate context to center of canvas
    context.translate(canvas.width / 2, canvas.height / 2);
    /*center the image*/

     // flip context horizontally
    context.scale(-1, 1); /*mirror image*/


    var imageObj = new Image();
    /*creating image object*/
    imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

    imageObj.onload = function() {

      context.drawImage(imageObj, -imageObj.width / 2, -imageObj.height / 2);
      /* draw and center the image*/
      context.restore();
      context.save();
    };
    var dataURL = canvas.toDataURL("image/jpeg");
    /* canvas to url  */
    document.getElementById('canvasImg').src = dataURL;
     // using url as source for img with id canvasImg
  </script>
</body>

</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Dragos Cocos
  • 49
  • 2
  • 7

1 Answers1

1

There are mainly two issues here.

1.) You are converting canvas to dataURL even before canvas has been drawn. Add a delay to see the result.

setTimeout(function(){
          var dataURL = canvas.toDataURL("image/jpeg");
          console.log(dataURL);
          /* canvas to url  */
          document.getElementById('canvasImg').src = dataURL;
           // using url as source for img with id canvasImg
    },2000);

2.) You are loading image from different server, so it will raise security issue. See error in your console. "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported."

Now, to avoid this error you can download the image to your local machine. Change image path to point where you stored your image on local machine. This will work.

Asit
  • 458
  • 4
  • 14