Reputation: 75
I have an input box that accepts a url of an image, when the submit button is clicked the url is got by a javascript function, which updates a canvas and an image object on the page.
The image is located fine, and it appears in the image object and canvas object, but very shortly after is disappears.
<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>
I have used the updateCanvas() function elsewhere, where it works fine and the image stays. Both of the alerts in the javascript functions appear as expected, but the image does not stay in the canvas/image object.
Upvotes: 0
Views: 1002
Reputation: 1
Either you can prevent the submit action of the form or change the input type to button and attach submitImage function to the click event of the button and remove the submitImage from form submit
{code}
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;
};
return false;
}
{code}
Upvotes: 0
Reputation: 3943
You're submitting the form, that involves re-loading the page, so I guess it shows the image briefly, and then reloads, emptying the canvas.
Use onclick
on the button instead of onsubmit
on the form to avoid reloading, and make the button not submit the form by changing from an input type="submit"
to a button type="button"
:
<button type="button" onclick="submitImage()">Submit</button>
Upvotes: 2