0

I want to have a textbox which a user can paste an image URL into and an enter button which, upon clicking, will draw the image on the canvas. This is my canvas and textbox/enter button.

<body>
<input type="text" id="input"/><input type="button" value="Enter" onclick="useImage()">
<canvas id="canvas" width="600" height="400" style="border:1px solid grey;">
</body>

Then I know I should have a function in my javascript which allows this and references the canvas:

<script>
function useImage(){
  var c = document.getElementById("canvas");
  var ctx = c.getContext("2d"); //WHAT GOES IN HERE?
  ctx.drawImage(img,0,0,600,400);   
</script>

But I'm not sure how to make my function work, can anybody help please? I want the image to fill the whole canvas which is 600x400.

SJ6789
  • 3
  • 1
  • possible duplicate of [Drawing an image from a data URL to a canvas](http://stackoverflow.com/questions/4773966/drawing-an-image-from-a-data-url-to-a-canvas) – Steve Wellens Nov 28 '14 at 21:23

1 Answers1

0

A simple way is to create the image element on the page and then let drawImage pull the data from there. You might try something like this

  function useImage(ev){
    // create the image element
    var img = document.createElement('img');
    // get the image url from the input box
    img.src = document.getElementById('input').value;

    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    ctx.drawImage(img,0,0,600,400);   
  }
mr rogers
  • 3,200
  • 1
  • 19
  • 31