I am trying to render an image uploaded by the user using an <input> tag with an on change event listener in javascript. However the image will not render.
All of the code below is the browser rendering static files on my local machine. There is no HTTP request/response cycle happening.
Here is my Javascript:
//test to see if I can auto render an image from a browser function
function loadImage(event) {
image_element = document.createElement("img");
image_element.src = URL.createObjectURL(event.target.files[0]);
var canvas_wdith = image_element.width;
var canvas_height = image_element.height;
canvas_element.width = canvas_wdith;
canvas_element.height = canvas_height;
context = canvas_element.getContext("2d");
context.drawImage(image_element, 0, 0);
URL.revokeObjectURL(image_element.src);
}
// get both the input and canvas tags from the page.
file = document.getElementById("picture");
canvas_element = document.getElementById("current_image");
file.addEventListener("change", loadImage);
Here is the html I’m using to render the page:
<!DOCTYPE html>
<!--modified from template found at https://www.freecodecamp.org/news/basic-html5-template-boilerplate-code-example -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Color Descriptor Application</title>
<link rel="stylesheet" href="">
</head>
<body>
<h1>Color Descriptor Application</h1>
<label for="picture"> Choose a picture</label>
<input type="file" id="picture" accept="image/*"/>
<p></p>
<canvas id="current_image">
</canvas>
<script src="index.js"></script>
</body>
</html>
Things I have already tried:
- I have wrapped the last two lines of the loadImage function into an anonymous function that is triggered in an onload event handler like this stackOverflow example:
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
-
I ran this code in the firefox debugger. I got no syntax or type errors. When I manually step through the code, The image renders to the canvas as I want. I have no clue what is causing my image to not load when the code is ran outside of the debugger.
-
I have already consulted the documentation on the createObjectURL method: URL: createObjectURL() static method - Web APIs | MDN
-
I have already consulted the documentation on using files: Using files from web applications - Web APIs | MDN
-
I have already consulted the documentation on using images as a drawing source for a canvas: CanvasRenderingContext2D: drawImage() method - Web APIs | MDN
-
I read through the tutorial on using images with canvas: Using images - Web APIs | MDN
None of these gave me any hints as to what was wrong. I know I did something wrong with one of the API calls. I’m just not sure what.