How to add image to canvas









up vote
82
down vote

favorite
31












I'm experimenting a bit with the new canvas element in HTML.



I simply want to add an image to the canvas but it doesn't work for some reason.



I have the following code:



HTML



<canvas id="viewport"></canvas>


CSS



canvas#viewport border: 1px solid white; width: 900px; 


JS



var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()

base_image = new Image();
base_image.src = 'img/base.png';
context.drawImage(base_image, 100, 100);



The image exists and I get no JavaScript errors. The image just doesn't display.



It must be something really simple I've missed...










share|improve this question



























    up vote
    82
    down vote

    favorite
    31












    I'm experimenting a bit with the new canvas element in HTML.



    I simply want to add an image to the canvas but it doesn't work for some reason.



    I have the following code:



    HTML



    <canvas id="viewport"></canvas>


    CSS



    canvas#viewport border: 1px solid white; width: 900px; 


    JS



    var canvas = document.getElementById('viewport'),
    context = canvas.getContext('2d');

    make_base();

    function make_base()

    base_image = new Image();
    base_image.src = 'img/base.png';
    context.drawImage(base_image, 100, 100);



    The image exists and I get no JavaScript errors. The image just doesn't display.



    It must be something really simple I've missed...










    share|improve this question

























      up vote
      82
      down vote

      favorite
      31









      up vote
      82
      down vote

      favorite
      31






      31





      I'm experimenting a bit with the new canvas element in HTML.



      I simply want to add an image to the canvas but it doesn't work for some reason.



      I have the following code:



      HTML



      <canvas id="viewport"></canvas>


      CSS



      canvas#viewport border: 1px solid white; width: 900px; 


      JS



      var canvas = document.getElementById('viewport'),
      context = canvas.getContext('2d');

      make_base();

      function make_base()

      base_image = new Image();
      base_image.src = 'img/base.png';
      context.drawImage(base_image, 100, 100);



      The image exists and I get no JavaScript errors. The image just doesn't display.



      It must be something really simple I've missed...










      share|improve this question















      I'm experimenting a bit with the new canvas element in HTML.



      I simply want to add an image to the canvas but it doesn't work for some reason.



      I have the following code:



      HTML



      <canvas id="viewport"></canvas>


      CSS



      canvas#viewport border: 1px solid white; width: 900px; 


      JS



      var canvas = document.getElementById('viewport'),
      context = canvas.getContext('2d');

      make_base();

      function make_base()

      base_image = new Image();
      base_image.src = 'img/base.png';
      context.drawImage(base_image, 100, 100);



      The image exists and I get no JavaScript errors. The image just doesn't display.



      It must be something really simple I've missed...







      javascript html5 canvas






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 30 '13 at 12:51

























      asked May 15 '11 at 21:28









      PeeHaa

      49.3k41165240




      49.3k41165240






















          3 Answers
          3






          active

          oldest

          votes

















          up vote
          172
          down vote



          accepted










          Maybe you should have to wait until the image is loaded before you draw it. Try this instead:



          var canvas = document.getElementById('viewport'),
          context = canvas.getContext('2d');

          make_base();

          function make_base()

          base_image = new Image();
          base_image.src = 'img/base.png';
          base_image.onload = function()
          context.drawImage(base_image, 0, 0);




          I.e. draw the image in the onload callback of the image.






          share|improve this answer


















          • 1




            Will that work with images fetched over URL?
            – swogger
            Nov 13 '14 at 12:53






          • 5




            @swogger rather thank ask anything, try out. That worked perfectly. Make sure you check first the img size of the source, otherwise will be cropped unless you use full function context.drawImage(base_image, 0, 0, 200, 200);. That would draw base_img from 0px position, with draw area of 200x200px.
            – erm3nda
            Feb 16 '15 at 4:52






          • 1




            This was exactly my case. I was loading some blob data into canvas using new Image and wondering why it was always showing me a previous image. Turns out even if I'm loading an image from a variable I still have to wait for the onload to happen. Thank you!
            – aexl
            Mar 16 '16 at 22:27










          • How to add image style ?
            – Sagar Rawal
            Sep 20 '16 at 12:55

















          up vote
          1
          down vote













          here is the sample code to draw image on canvas-



          $("#selectedImage").change(function(e) 

          var URL = window.URL;
          var url = URL.createObjectURL(e.target.files[0]);
          img.src = url;

          img.onload = function()
          var canvas = document.getElementById("myCanvas");
          var ctx = canvas.getContext("2d");

          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0, 500, 500);
          );


          In the above code selectedImage is an input control which can be used to browse image on system.
          For more details of sample code to draw image on canvas while maintaining the aspect ratio:



          http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html






          share|improve this answer





























            up vote
            1
            down vote













            In my case, I was mistaken the function parameters, which are:



            context.drawImage(image, left, top);
            context.drawImage(image, left, top, width, height);


            If you expect them to be



            context.drawImage(image, width, height);


            you will place the image just outside the canvas with the same effects as described in the question.






            share|improve this answer




















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













               

              draft saved


              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6011378%2fhow-to-add-image-to-canvas%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              172
              down vote



              accepted










              Maybe you should have to wait until the image is loaded before you draw it. Try this instead:



              var canvas = document.getElementById('viewport'),
              context = canvas.getContext('2d');

              make_base();

              function make_base()

              base_image = new Image();
              base_image.src = 'img/base.png';
              base_image.onload = function()
              context.drawImage(base_image, 0, 0);




              I.e. draw the image in the onload callback of the image.






              share|improve this answer


















              • 1




                Will that work with images fetched over URL?
                – swogger
                Nov 13 '14 at 12:53






              • 5




                @swogger rather thank ask anything, try out. That worked perfectly. Make sure you check first the img size of the source, otherwise will be cropped unless you use full function context.drawImage(base_image, 0, 0, 200, 200);. That would draw base_img from 0px position, with draw area of 200x200px.
                – erm3nda
                Feb 16 '15 at 4:52






              • 1




                This was exactly my case. I was loading some blob data into canvas using new Image and wondering why it was always showing me a previous image. Turns out even if I'm loading an image from a variable I still have to wait for the onload to happen. Thank you!
                – aexl
                Mar 16 '16 at 22:27










              • How to add image style ?
                – Sagar Rawal
                Sep 20 '16 at 12:55














              up vote
              172
              down vote



              accepted










              Maybe you should have to wait until the image is loaded before you draw it. Try this instead:



              var canvas = document.getElementById('viewport'),
              context = canvas.getContext('2d');

              make_base();

              function make_base()

              base_image = new Image();
              base_image.src = 'img/base.png';
              base_image.onload = function()
              context.drawImage(base_image, 0, 0);




              I.e. draw the image in the onload callback of the image.






              share|improve this answer


















              • 1




                Will that work with images fetched over URL?
                – swogger
                Nov 13 '14 at 12:53






              • 5




                @swogger rather thank ask anything, try out. That worked perfectly. Make sure you check first the img size of the source, otherwise will be cropped unless you use full function context.drawImage(base_image, 0, 0, 200, 200);. That would draw base_img from 0px position, with draw area of 200x200px.
                – erm3nda
                Feb 16 '15 at 4:52






              • 1




                This was exactly my case. I was loading some blob data into canvas using new Image and wondering why it was always showing me a previous image. Turns out even if I'm loading an image from a variable I still have to wait for the onload to happen. Thank you!
                – aexl
                Mar 16 '16 at 22:27










              • How to add image style ?
                – Sagar Rawal
                Sep 20 '16 at 12:55












              up vote
              172
              down vote



              accepted







              up vote
              172
              down vote



              accepted






              Maybe you should have to wait until the image is loaded before you draw it. Try this instead:



              var canvas = document.getElementById('viewport'),
              context = canvas.getContext('2d');

              make_base();

              function make_base()

              base_image = new Image();
              base_image.src = 'img/base.png';
              base_image.onload = function()
              context.drawImage(base_image, 0, 0);




              I.e. draw the image in the onload callback of the image.






              share|improve this answer














              Maybe you should have to wait until the image is loaded before you draw it. Try this instead:



              var canvas = document.getElementById('viewport'),
              context = canvas.getContext('2d');

              make_base();

              function make_base()

              base_image = new Image();
              base_image.src = 'img/base.png';
              base_image.onload = function()
              context.drawImage(base_image, 0, 0);




              I.e. draw the image in the onload callback of the image.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 15 at 21:38

























              answered May 15 '11 at 21:32









              Thomas

              6,62242032




              6,62242032







              • 1




                Will that work with images fetched over URL?
                – swogger
                Nov 13 '14 at 12:53






              • 5




                @swogger rather thank ask anything, try out. That worked perfectly. Make sure you check first the img size of the source, otherwise will be cropped unless you use full function context.drawImage(base_image, 0, 0, 200, 200);. That would draw base_img from 0px position, with draw area of 200x200px.
                – erm3nda
                Feb 16 '15 at 4:52






              • 1




                This was exactly my case. I was loading some blob data into canvas using new Image and wondering why it was always showing me a previous image. Turns out even if I'm loading an image from a variable I still have to wait for the onload to happen. Thank you!
                – aexl
                Mar 16 '16 at 22:27










              • How to add image style ?
                – Sagar Rawal
                Sep 20 '16 at 12:55












              • 1




                Will that work with images fetched over URL?
                – swogger
                Nov 13 '14 at 12:53






              • 5




                @swogger rather thank ask anything, try out. That worked perfectly. Make sure you check first the img size of the source, otherwise will be cropped unless you use full function context.drawImage(base_image, 0, 0, 200, 200);. That would draw base_img from 0px position, with draw area of 200x200px.
                – erm3nda
                Feb 16 '15 at 4:52






              • 1




                This was exactly my case. I was loading some blob data into canvas using new Image and wondering why it was always showing me a previous image. Turns out even if I'm loading an image from a variable I still have to wait for the onload to happen. Thank you!
                – aexl
                Mar 16 '16 at 22:27










              • How to add image style ?
                – Sagar Rawal
                Sep 20 '16 at 12:55







              1




              1




              Will that work with images fetched over URL?
              – swogger
              Nov 13 '14 at 12:53




              Will that work with images fetched over URL?
              – swogger
              Nov 13 '14 at 12:53




              5




              5




              @swogger rather thank ask anything, try out. That worked perfectly. Make sure you check first the img size of the source, otherwise will be cropped unless you use full function context.drawImage(base_image, 0, 0, 200, 200);. That would draw base_img from 0px position, with draw area of 200x200px.
              – erm3nda
              Feb 16 '15 at 4:52




              @swogger rather thank ask anything, try out. That worked perfectly. Make sure you check first the img size of the source, otherwise will be cropped unless you use full function context.drawImage(base_image, 0, 0, 200, 200);. That would draw base_img from 0px position, with draw area of 200x200px.
              – erm3nda
              Feb 16 '15 at 4:52




              1




              1




              This was exactly my case. I was loading some blob data into canvas using new Image and wondering why it was always showing me a previous image. Turns out even if I'm loading an image from a variable I still have to wait for the onload to happen. Thank you!
              – aexl
              Mar 16 '16 at 22:27




              This was exactly my case. I was loading some blob data into canvas using new Image and wondering why it was always showing me a previous image. Turns out even if I'm loading an image from a variable I still have to wait for the onload to happen. Thank you!
              – aexl
              Mar 16 '16 at 22:27












              How to add image style ?
              – Sagar Rawal
              Sep 20 '16 at 12:55




              How to add image style ?
              – Sagar Rawal
              Sep 20 '16 at 12:55












              up vote
              1
              down vote













              here is the sample code to draw image on canvas-



              $("#selectedImage").change(function(e) 

              var URL = window.URL;
              var url = URL.createObjectURL(e.target.files[0]);
              img.src = url;

              img.onload = function()
              var canvas = document.getElementById("myCanvas");
              var ctx = canvas.getContext("2d");

              ctx.clearRect(0, 0, canvas.width, canvas.height);
              ctx.drawImage(img, 0, 0, 500, 500);
              );


              In the above code selectedImage is an input control which can be used to browse image on system.
              For more details of sample code to draw image on canvas while maintaining the aspect ratio:



              http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html






              share|improve this answer


























                up vote
                1
                down vote













                here is the sample code to draw image on canvas-



                $("#selectedImage").change(function(e) 

                var URL = window.URL;
                var url = URL.createObjectURL(e.target.files[0]);
                img.src = url;

                img.onload = function()
                var canvas = document.getElementById("myCanvas");
                var ctx = canvas.getContext("2d");

                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0, 500, 500);
                );


                In the above code selectedImage is an input control which can be used to browse image on system.
                For more details of sample code to draw image on canvas while maintaining the aspect ratio:



                http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html






                share|improve this answer
























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  here is the sample code to draw image on canvas-



                  $("#selectedImage").change(function(e) 

                  var URL = window.URL;
                  var url = URL.createObjectURL(e.target.files[0]);
                  img.src = url;

                  img.onload = function()
                  var canvas = document.getElementById("myCanvas");
                  var ctx = canvas.getContext("2d");

                  ctx.clearRect(0, 0, canvas.width, canvas.height);
                  ctx.drawImage(img, 0, 0, 500, 500);
                  );


                  In the above code selectedImage is an input control which can be used to browse image on system.
                  For more details of sample code to draw image on canvas while maintaining the aspect ratio:



                  http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html






                  share|improve this answer














                  here is the sample code to draw image on canvas-



                  $("#selectedImage").change(function(e) 

                  var URL = window.URL;
                  var url = URL.createObjectURL(e.target.files[0]);
                  img.src = url;

                  img.onload = function()
                  var canvas = document.getElementById("myCanvas");
                  var ctx = canvas.getContext("2d");

                  ctx.clearRect(0, 0, canvas.width, canvas.height);
                  ctx.drawImage(img, 0, 0, 500, 500);
                  );


                  In the above code selectedImage is an input control which can be used to browse image on system.
                  For more details of sample code to draw image on canvas while maintaining the aspect ratio:



                  http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 3 '16 at 9:29

























                  answered Nov 3 '16 at 8:48









                  nvivekgoyal

                  167313




                  167313




















                      up vote
                      1
                      down vote













                      In my case, I was mistaken the function parameters, which are:



                      context.drawImage(image, left, top);
                      context.drawImage(image, left, top, width, height);


                      If you expect them to be



                      context.drawImage(image, width, height);


                      you will place the image just outside the canvas with the same effects as described in the question.






                      share|improve this answer
























                        up vote
                        1
                        down vote













                        In my case, I was mistaken the function parameters, which are:



                        context.drawImage(image, left, top);
                        context.drawImage(image, left, top, width, height);


                        If you expect them to be



                        context.drawImage(image, width, height);


                        you will place the image just outside the canvas with the same effects as described in the question.






                        share|improve this answer






















                          up vote
                          1
                          down vote










                          up vote
                          1
                          down vote









                          In my case, I was mistaken the function parameters, which are:



                          context.drawImage(image, left, top);
                          context.drawImage(image, left, top, width, height);


                          If you expect them to be



                          context.drawImage(image, width, height);


                          you will place the image just outside the canvas with the same effects as described in the question.






                          share|improve this answer












                          In my case, I was mistaken the function parameters, which are:



                          context.drawImage(image, left, top);
                          context.drawImage(image, left, top, width, height);


                          If you expect them to be



                          context.drawImage(image, width, height);


                          you will place the image just outside the canvas with the same effects as described in the question.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 7 '17 at 10:08









                          Marc

                          8,34923270




                          8,34923270



























                               

                              draft saved


                              draft discarded















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6011378%2fhow-to-add-image-to-canvas%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Darth Vader #20

                              How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                              Ondo