javascript - 提交后图像出现然后消失

标签 javascript html image

我有一个输入框,它接受图像的 URL,当单击提交按钮时,JavaScript 函数将获取 URL,该函数会更新页面上的 Canvas 和图像对象。

图像位置很好,它出现在图像对象和 Canvas 对象中,但很快就消失了。

 <canvas id = "edit_canvas" width = "600" height = "600"></canvas>
  <img src= "images/placeholder.png" alt="Image Cannot Be Displayed" id = "edit_pic">

  <form onsubmit = "submitImage()">
    Custom Picture: <input type="url" name="pic_url" id ="input_url"><br>
    <input type="submit">
  </form>

  <script type="text/javascript">
   function submitImage(){
       var img = new Image();
       var url = document.getElementById("input_url").value;
       img.src = url;
       img.onload = function(){
           alert("img has loaded");
           updateCanvas(img);
           document.getElementById("edit_pic").src = url;
       };   
   }
   function updateCanvas(img){
       alert("updateCanvas called");
       var c =document.getElementById("edit_canvas");
       var ctx=c.getContext("2d");
       ctx.drawImage(img,0,0);
   }
   </script>

我在其他地方使用了 updateCanvas() 函数,它工作正常并且图像保持不变。 javascript 函数中的两个警报均按预期显示,但图像不会保留在 canvas/image 对象中。

最佳答案

您正在提交表单,这涉及到重新加载页面,因此我猜它会短暂显示图像,然后重新加载,清空 Canvas 。

在按钮上使用 onclick 而不是表单上的 onsubmit 以避免重新加载,并通过更改 input type= 使按钮不提交表单“提交”button type="button":

<button type="button" onclick="submitImage()">Submit</button>

关于javascript - 提交后图像出现然后消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27133638/

相关文章:

php - 将 Google 图表另存为图片

javascript - 本地目录查看器和从 Intranet 浏览器拖放

javascript - 如果在其字段中包含 SQL 语句,则验证对象

html - 如何在不影响其他部分的情况下将我的 Wordpress 主页上的一个小部件作为目标?

javascript - 我可以要求在网站上阅读短信吗

android - 图像下载器类的枚举声明有错误

javascript - 发生mousedown时如何防止IE中的焦点事件

javascript - 将 d3.csv 响应分配给全局变量

html - Firefox 不呈现字体 : What is usually the root of the issue?

javascript - 如何获取图像的实际尺寸