我有一个输入框,它接受图像的 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/