1

Beginner dev here. One of my lessons is to place (and transform) an image into canvas using only the Image() constructor. That is to say, NOT creating a variable that is linked to an image element located in the HTML code. Consider the following:

<script type = "text/javascript">
    function draw(){
        var drawing = document.getElementById("drawing");
        var con = drawing.getContext("2d");
        var dog = new Image();
        dog.src = "dog.jpg";

        //begin transformation

        con.save();
        con.translate(200, 100);
        con.rotate(25*Math.PI/180);
        con.drawImage(dog, 0, 0);
        con.restore();
    }
</script>`

I used some CSS to outline the canvas in red and move it closer to the center of the screen for visibility's sake. Despite all my efforts, Chrome will not display the image, but IE will. However, IE does require a prompt for the image to show: "Internet Explorer restricted this webpage from running scripts or ActiveX controls." After allowing this with the button that they provide, the image displays.

Chrome, on the other hand, does not provide a prompt of any kind. I've looked around extensively for an answer to this and even went so far as to enable/disable all the script running options and extensions (popups and downloads included) to no avail.

Just to be clear, I'm aware that there are other ways for the image to display properly, but my concern is for why it won't work with Chrome in this context.

  • Possible duplicate of [CanvasContext2D drawImage() issue \[onload and CORS\]](http://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue-onload-and-cors) – Kaiido Jan 09 '16 at 08:18

1 Answers1

2

Your code is not waiting for the image to load:

    var drawing = document.getElementById("drawing");
    var con = drawing.getContext("2d");
    var dog = new Image();

    //begin transformation
    dog.onload = function() {
      con.save();
      con.translate(200, 100);
      con.rotate(25*Math.PI/180);
      con.drawImage(dog, 0, 0);
      con.restore();
    };

    dog.src = "dog.jpg";

By putting the image copy code into the "load" handler, you ensure that the image pixels are actually available. There's no significant performance penalty to pay if the image happens to already be in the browser cache.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • This worked, thanks. Do you know why IE handles this differently from Chrome? IE does not seem to require a load handler for the image to display and only prompts the user to accept the script to run. – user5765119 Jan 10 '16 at 00:22
  • You need that for any browser, but IE behaves a little differently than others if the image is in the browser cache. – Pointy Jan 10 '16 at 00:23