简体   繁体   English

让用户输入图片网址并将其绘制在html5画布上

[英]Let user input image URL and draw this on the html5 canvas

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. 我希望有一个文本框,用户可以将图像URL粘贴到其中,并有一个输入按钮,单击该按钮将在画布上绘制图像。 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: 然后我知道我应该在我的javascript中有一个函数,允许该函数并引用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. 我希望图像填充整个600x400的画布。

A simple way is to create the image element on the page and then let drawImage pull the data from there. 一种简单的方法是在页面上创建image元素,然后让drawImage从那里提取数据。 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);   
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM