Trying to store user image to server. Very new to this, so I just started looking around and I found the following code:
function getBase64Image( imgElem ) {
let canvas = document.createElement( 'canvas' );
canvas.width = imgElem.clientWidth;
canvas.height = imgElem.clientHeight;
let ctx = canvas.getContext( '2d' );
ctx.drawImage(imgElem, 0, 0);
let dataURL = canvas.toDataURL( 'image/png' );
return dataURL.replace( /^data:image\/(png|jpg);base64,/, '' );
}
I'm using this function to store a user inputed image on my local server, but I get the following error:
factories.js:1 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'getBase64Image @ factories.js:1SubmitRecipe @ recipe-submission.js:1onclick @ submitrecipe:43
I am grabbing the image with an input tag that has type
set to file
. Here is my code:
HTML
<label>Image</label>
<span class='err-message' id='image-err'></span></br>
<input type="file" id='image'>
JS
function SubmitRecipe() {
//sets the recipe object and its keys
let recipe = { alias: null, description: null, category: null, instructions: null, image: null };
let img = document.getElementById( 'image' );
recipe.image = JSON.stringify( getBase64Image( img ) );
}
I believe the problem has to do with the fact that the element image
is an HTMLInputElement
, and that isn't what drawImage
expects. I just have no idea how to solve it.
All help is appreciated.