英文:
How to store and display uploaded image in JS?
问题
以下是您要翻译的内容:
const log = document.getElementById("log");
possibleIngredients.length = 0;
let uniqueIngredients = [];
const recipes = {};
const recipeAdder = document.getElementById('RecipeAdder');
const recipeName = document.getElementById('inputrecipetitle');
const searchButton = document.getElementById('searchbutton');
const threshold = 3
const compareButton = document.getElementById('submitknowningredients');
function addRecipe(title, input){
const ingredients = Array.from(input).map(input => input.value);
recipes[title] = ingredients;
}
//below is the levenshtein function, basically just allowing error in between search and title
function levenshtein(a, b) {
const matrix = [];
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
}
}
}
return matrix[b.length][a.length];
}
recipeAdder.addEventListener("submit", function(e){
e.preventDefault();
const input = document.querySelectorAll('.ingredients');
const inputArray = Array from(input);
const recipeLink = document.getElementById('recipelinksubmit');
const image = document.getElementById('imageupload');
document.body.style.backgroundImage = `url(${image})`;
console.log(image);
addRecipe(recipeName.value, inputArray);
input.forEach(function(input){
possibleIngredients.push(input.value);
input.value = '';
});
uniqueIngredients = [...new Set(possibleIngredients)];
});
searchButton.addEventListener("click", function(e){
e.preventDefault();
const recipeSearch = document.getElementById('recipesearch');
for (const title in recipes){
const normalizedSearch = recipeSearch.value.toLowerCase();
const normalizedTitle = title.toLowerCase();
const distance = levenshtein(normalizedSearch, normalizedTitle);
if(distance <= threshold){
console.log(recipes[title]);
}
}
})
compareButton.addEventListener('click', function(e){
e.preventDefault();
const ingredientsInput = document.getElementById('myingredients');
const myIngredients = ingredientsInput.value.split(',').map(ingredient => ingredient.trim().toLowerCase());
for(const title in recipes){
const recipeIngredients = recipes[title].map(ingredient => ingredient.toLowerCase());
const isMatch = recipeIngredients.every(ingredient => myIngredients.includes(ingredient));
if(isMatch){
console.log(`you can make ${title} with your ingredients`);
}
}
})
log.addEventListener('click', function(){
console.log(uniqueIngredients);
for(const title in recipes){
console.log(title, recipes[title]);
}
});
<html lang="en">
<head>
<link rel="stylesheet" href="recipefinder.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Recipe Finder</title>
</head>
<body>
<h1 class="scroll">Possible Recipes</h1>
<h2 class="hadingredients">Ingredients In Stock:</h2>
<div class="possiblerecipes">
<img src="img/brocolli_cheese.jpg" class = "pic1">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/GarlicBread.jpg" class="pic2">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/MangoCandy.jpg" class="pic3">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/Meatballs.jpg" class = "pic4">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/brocolli_cheese.jpg" class = "pic5">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/GarlicBread.jpg" class="pic6">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/MangoCandy.jpg" class="pic7">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/Meatballs.jpg" class = "pic8">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/brocolli_cheese.jpg" class = "pic9">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/GarlicBread.jpg" class="pic10">
<a class="init" href="https://google.com">
<details>
<summary>英文:</summary>
I'm pretty new to JS and HTML, and this is a very simple question, but I haven't found any straightforward solution. What I'm trying to do is in the form submission, there is a file upload. When the form is submitted, I want to store the uploaded image in an object under the "Recipe name", I can do all that, what I need help in is figuring out how to store uploaded images and then redisplay them as an image all on the html page.
In this code, I set image to the getelementbyid "imageupload" and just to test it out, when the button is pushed, it would set the background image to the url. I know just setting it equal to image shouldn't be the URL, but I've tried image.value and image.src and a couple others, and none of them worked, so I just need to know how to get something like this to work.
const possibleIngredients = [];
const log = document.getElementById("log");
possibleIngredients.length = 0;
let uniqueIngredients = [];
const recipes = {};
const recipeAdder = document.getElementById('RecipeAdder');
const recipeName = document.getElementById('inputrecipetitle');
const searchButton = document.getElementById('searchbutton');
const threshold = 3
const compareButton = document.getElementById('submitknowningredients');
function addRecipe(title, input){
const ingredients = Array.from(input).map(input => input.value);
recipes[title] = ingredients;
}
//below is the levenshtein function, basically just allowing error in between search and title
function levenshtein(a, b) {
const matrix = [];
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
}
}
}
return matrix[b.length][a.length];
}
recipeAdder.addEventListener("submit", function(e){
e.preventDefault();
const input = document.querySelectorAll('.ingredients');
const inputArray = Array.from(input);
const recipeLink = document.getElementById('recipelinksubmit');
const image = document.getElementById('imageupload');
document.body.style.backgroundImage = url(${image})
;
console.log(image);
addRecipe(recipeName.value, inputArray);
input.forEach(function(input){
possibleIngredients.push(input.value);
input.value = '';
});
uniqueIngredients = [...new Set(possibleIngredients)];
});
searchButton.addEventListener("click", function(e){
e.preventDefault();
const recipeSearch = document.getElementById('recipesearch');
for (const title in recipes){
const normalizedSearch = recipeSearch.value.toLowerCase();
const normalizedTitle = title.toLowerCase();
const distance = levenshtein(normalizedSearch, normalizedTitle);
if(distance <= threshold){
console.log(recipes[title]);
}
}
})
compareButton.addEventListener('click', function(e){
e.preventDefault();
const ingredientsInput = document.getElementById('myingredients');
const myIngredients = ingredientsInput.value.split(',').map(ingredient => ingredient.trim().toLowerCase());
for(const title in recipes){
const recipeIngredients = recipes[title].map(ingredient => ingredient.toLowerCase());
const isMatch = recipeIngredients.every(ingredient => myIngredients.includes(ingredient));
if(isMatch){
console.log(`you can make ${title} with your ingredients`);
}
}
})
log.addEventListener('click', function(){
console.log(uniqueIngredients);
for(const title in recipes){
console.log(title, recipes[title]);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="recipefinder.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Recipe Finder</title>
</head>
<body>
<h1 class="scroll">Possible Recipes</h1>
<h2 class="hadingredients">Ingredients In Stock:</h2>
<div class="possiblerecipes">
<img src="img/brocolli_cheese.jpg" class = "pic1">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/GarlicBread.jpg" class="pic2">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/MangoCandy.jpg" class="pic3">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/Meatballs.jpg" class = "pic4">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/brocolli_cheese.jpg" class = "pic5">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/GarlicBread.jpg" class="pic6">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/MangoCandy.jpg" class="pic7">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/Meatballs.jpg" class = "pic8">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/brocolli_cheese.jpg" class = "pic9">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/GarlicBread.jpg" class="pic10">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/MangoCandy.jpg" class="pic11">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/Meatballs.jpg" class = "pic12">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/brocolli_cheese.jpg" class = "pic13">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/GarlicBread.jpg" class="pic14">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/MangoCandy.jpg" class="pic15">
<a class="init" href="https://google.com">Placeholder</a>
<img src="img/Meatballs.jpg" class = "pic16">
<a class="init" href="https://google.com">Placeholder</a>
</div>
<div class="hadingredientslist">
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">✔️test</p>
<p class="hadingredient">❌test</p>
<p class="hadingredient">❌test</p>
</div>
<form id="RecipeAdder">
<label for="Enter your Recipe Name Here: ">Enter Your Recipe Name Here: </label>
<input type="text" id="inputrecipetitle"><br>
<label for="Enter Your Ingredients Below:">Enter Your Ingredients Below: </label><br>
<input type="text" id="ingredientspace1" class="ingredients"><br>
<input type="text" id="ingredientspace2" class="ingredients"><br>
<input type="text" id="ingredientspace3" class="ingredients"><br>
<input type="text" id="ingredientspace4" class="ingredients"><br>
<input type="text" id="ingredientspace5" class="ingredients"><br>
<input type="text" id="ingredientspace6" class="ingredients"><br>
<input type="text" id="ingredientspace7" class="ingredients"><br>
<input type="text" id="ingredientspace8" class="ingredients"><br>
<input type="text" id="ingredientspace9" class="ingredients"><br>
<input type="text" id="ingredientspace10" class="ingredients"><br>
<label for="link" >Enter The Recipe Link Here: </label>
<input type="text" id="recipelinksubmit" class="link"><br>
<input type="file" id="imageupload" class="file">
<button type="submit">Submit Recipe!</button>
</form>
<input type="text" id="recipesearch">
<button id="searchbutton">Search Me</button>
<br>
<input type="text" id="myingredients" placeholder="Enter Known Ingredients Here Seperated by a Comma"><br>
<button id="submitknowningredients">Look for Recipes!</button>
<button id="log">Log Me!</button>
<script src="recipefinder.js"></script>
</body>
</html>
</details>
# 答案1
**得分**: 1
以下是您要翻译的内容:
如果您只对设置容器元素的背景图像感兴趣(在这种情况下,文档主体),如上所述,您可能会发现以下简短的代码段有用。
您可以将事件监听器绑定到`file`输入字段,并处理对文件选择的任何更改。事件处理程序可以访问`files`属性 - 有关`File` API的信息,请参见[此处](https://developer.mozilla.org/en-US/docs/Web/API/File),有关在应用程序中使用此API的信息,请参见[此处](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications)。
有了对文件的引用,可以使用`FileReader` API来读取文件。
成功读取文件后,`FileReader`实例将触发`load`事件,该事件触发一个回调函数,用于创建一个新的`Image`,然后将其用作所选容器的`backgroundImage`属性。
浏览本地系统上的图像文件以设置为背景图像。
<details>
<summary>英文:</summary>
If you are only interested in setting the background image of a container element ( in this case the document.body ) as seems the case given the wording of the above you might find the following short snippet of use.
You bind an event listener to the `file` input field and process any changes made to the selection of files. The event handler has access to the `files` property - see [`here`](https://developer.mozilla.org/en-US/docs/Web/API/File) for information about the `File` api and [`here`](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications) about using this in applications.
With a reference to the file the [`FileReader`](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) api can be used to, funnily enough, read the file.
Upon successfully reading a file the FileReader instance will fire a `load` event which triggers a callback function that is used to create a new `Image` which in turn is then used as the `backgroundImage` property for the chosen container.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
document.querySelector('input[type="file"]').addEventListener('change',e=>{
let file=e.target.files[0];
let reader = new FileReader();
reader.onload=function( evt ){
let img=new Image();
img.onload=( e )=>{
document.body.style.backgroundImage=`url(${img.src})`;
/*
To obtain a "storable" string representation of the image
- write the image to a canvas and use `toDataURL` to get
the base64 encoded source data....
*/
let canvas=document.querySelector('canvas');
canvas.width=img.width;
canvas.height=img.height;
let ctxt=canvas.getContext('2d');
ctxt.drawImage( img, 0, 0 );
let imgstr=canvas.toDataURL( file.type );
ctxt.clearRect(0,0,ctxt.canvas.width,ctxt.canvas.height);
console.log( imgstr )
}
img.src = evt.target.result;
};
reader.readAsDataURL( file );
});
<!-- language: lang-css -->
canvas{display:none}
<!-- language: lang-html -->
<input type='file' />
<canvas></canvas>
<!-- end snippet -->
Browse for a image file on your local system to set as the background image.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论