css 如何在JS中存储和显示上传的图像?

ryevplcw  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(110)

我是JS和HTML的新手,这是一个非常简单的问题,但我还没有找到任何直接的解决方案。我试图做的是在表单提交中,有一个文件上传。当表单提交时,我想将上传的图像存储在“Recipe name”下的对象中,我可以做到这一切,我需要的帮助是弄清楚如何存储上传的图像,然后重新显示它们作为一个图像都在html页面上。
在这段代码中,我将image设置为getelementbyid“imageupload”,只是为了测试一下,当按钮被按下时,它会将背景图像设置为URL。我知道只是将其设置为image不应该是URL,但我已经尝试了image.value和image.src以及其他几个,它们都没有工作,所以我只需要知道如何让这样的东西工作。

  1. const possibleIngredients = [];
  2. const log = document.getElementById("log");
  3. possibleIngredients.length = 0;
  4. let uniqueIngredients = [];
  5. const recipes = {};
  6. const recipeAdder = document.getElementById('RecipeAdder');
  7. const recipeName = document.getElementById('inputrecipetitle');
  8. const searchButton = document.getElementById('searchbutton');
  9. const threshold = 3
  10. const compareButton = document.getElementById('submitknowningredients');
  11. function addRecipe(title, input){
  12. const ingredients = Array.from(input).map(input => input.value);
  13. recipes[title] = ingredients;
  14. }
  15. //below is the levenshtein function, basically just allowing error in between search and title
  16. function levenshtein(a, b) {
  17. const matrix = [];
  18. for (let i = 0; i <= b.length; i++) {
  19. matrix[i] = [i];
  20. }
  21. for (let j = 0; j <= a.length; j++) {
  22. matrix[0][j] = j;
  23. }
  24. for (let i = 1; i <= b.length; i++) {
  25. for (let j = 1; j <= a.length; j++) {
  26. if (b.charAt(i - 1) === a.charAt(j - 1)) {
  27. matrix[i][j] = matrix[i - 1][j - 1];
  28. } else {
  29. matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
  30. }
  31. }
  32. }
  33. return matrix[b.length][a.length];
  34. }
  35. recipeAdder.addEventListener("submit", function(e){
  36. e.preventDefault();
  37. const input = document.querySelectorAll('.ingredients');
  38. const inputArray = Array.from(input);
  39. const recipeLink = document.getElementById('recipelinksubmit');
  40. const image = document.getElementById('imageupload');
  41. document.body.style.backgroundImage = `url(${image})`;
  42. console.log(image);
  43. addRecipe(recipeName.value, inputArray);
  44. input.forEach(function(input){
  45. possibleIngredients.push(input.value);
  46. input.value = '';
  47. });
  48. uniqueIngredients = [...new Set(possibleIngredients)];
  49. });
  50. searchButton.addEventListener("click", function(e){
  51. e.preventDefault();
  52. const recipeSearch = document.getElementById('recipesearch');
  53. for (const title in recipes){
  54. const normalizedSearch = recipeSearch.value.toLowerCase();
  55. const normalizedTitle = title.toLowerCase();
  56. const distance = levenshtein(normalizedSearch, normalizedTitle);
  57. if(distance <= threshold){
  58. console.log(recipes[title]);
  59. }
  60. }
  61. })
  62. compareButton.addEventListener('click', function(e){
  63. e.preventDefault();
  64. const ingredientsInput = document.getElementById('myingredients');
  65. const myIngredients = ingredientsInput.value.split(',').map(ingredient => ingredient.trim().toLowerCase());
  66. for(const title in recipes){
  67. const recipeIngredients = recipes[title].map(ingredient => ingredient.toLowerCase());
  68. const isMatch = recipeIngredients.every(ingredient => myIngredients.includes(ingredient));
  69. if(isMatch){
  70. console.log(`you can make ${title} with your ingredients`);
  71. }
  72. }
  73. })
  74. log.addEventListener('click', function(){
  75. console.log(uniqueIngredients);
  76. for(const title in recipes){
  77. console.log(title, recipes[title]);
  78. }
  79. });
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <link rel="stylesheet" href="recipefinder.css">
  5. <meta charset="UTF-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>Recipe Finder</title>
  9. </head>
  10. <body>
  11. <h1 class="scroll">Possible Recipes</h1>
  12. <h2 class="hadingredients">Ingredients In Stock:</h2>
  13. <div class="possiblerecipes">
  14. <img src="img/brocolli_cheese.jpg" class = "pic1">
  15. <a class="init" href="https://google.com">Placeholder</a>
  16. <img src="img/GarlicBread.jpg" class="pic2">
  17. <a class="init" href="https://google.com">Placeholder</a>
  18. <img src="img/MangoCandy.jpg" class="pic3">
  19. <a class="init" href="https://google.com">Placeholder</a>
  20. <img src="img/Meatballs.jpg" class = "pic4">
  21. <a class="init" href="https://google.com">Placeholder</a>
  22. <img src="img/brocolli_cheese.jpg" class = "pic5">
  23. <a class="init" href="https://google.com">Placeholder</a>
  24. <img src="img/GarlicBread.jpg" class="pic6">
  25. <a class="init" href="https://google.com">Placeholder</a>
  26. <img src="img/MangoCandy.jpg" class="pic7">
  27. <a class="init" href="https://google.com">Placeholder</a>
  28. <img src="img/Meatballs.jpg" class = "pic8">
  29. <a class="init" href="https://google.com">Placeholder</a>
  30. <img src="img/brocolli_cheese.jpg" class = "pic9">
  31. <a class="init" href="https://google.com">Placeholder</a>
  32. <img src="img/GarlicBread.jpg" class="pic10">
  33. <a class="init" href="https://google.com">Placeholder</a>
  34. <img src="img/MangoCandy.jpg" class="pic11">
  35. <a class="init" href="https://google.com">Placeholder</a>
  36. <img src="img/Meatballs.jpg" class = "pic12">
  37. <a class="init" href="https://google.com">Placeholder</a>
  38. <img src="img/brocolli_cheese.jpg" class = "pic13">
  39. <a class="init" href="https://google.com">Placeholder</a>
  40. <img src="img/GarlicBread.jpg" class="pic14">
  41. <a class="init" href="https://google.com">Placeholder</a>
  42. <img src="img/MangoCandy.jpg" class="pic15">
  43. <a class="init" href="https://google.com">Placeholder</a>
  44. <img src="img/Meatballs.jpg" class = "pic16">
  45. <a class="init" href="https://google.com">Placeholder</a>
  46. </div>
  47. <div class="hadingredientslist">
  48. <p class="hadingredient">✔️test</p>
  49. <p class="hadingredient">✔️test</p>
  50. <p class="hadingredient">✔️test</p>
  51. <p class="hadingredient">✔️test</p>
  52. <p class="hadingredient">✔️test</p>
  53. <p class="hadingredient">✔️test</p>
  54. <p class="hadingredient">✔️test</p>
  55. <p class="hadingredient">✔️test</p>
  56. <p class="hadingredient">✔️test</p>
  57. <p class="hadingredient">✔️test</p>
  58. <p class="hadingredient">✔️test</p>
  59. <p class="hadingredient">❌test</p>
  60. <p class="hadingredient">❌test</p>
  61. </div>
  62. <form id="RecipeAdder">
  63. <label for="Enter your Recipe Name Here: ">Enter Your Recipe Name Here: </label>
  64. <input type="text" id="inputrecipetitle"><br>
  65. <label for="Enter Your Ingredients Below:">Enter Your Ingredients Below: </label><br>
  66. <input type="text" id="ingredientspace1" class="ingredients"><br>
  67. <input type="text" id="ingredientspace2" class="ingredients"><br>
  68. <input type="text" id="ingredientspace3" class="ingredients"><br>
  69. <input type="text" id="ingredientspace4" class="ingredients"><br>
  70. <input type="text" id="ingredientspace5" class="ingredients"><br>
  71. <input type="text" id="ingredientspace6" class="ingredients"><br>
  72. <input type="text" id="ingredientspace7" class="ingredients"><br>
  73. <input type="text" id="ingredientspace8" class="ingredients"><br>
  74. <input type="text" id="ingredientspace9" class="ingredients"><br>
  75. <input type="text" id="ingredientspace10" class="ingredients"><br>
  76. <label for="link" >Enter The Recipe Link Here: </label>
  77. <input type="text" id="recipelinksubmit" class="link"><br>
  78. <input type="file" id="imageupload" class="file">
  79. <button type="submit">Submit Recipe!</button>
  80. </form>
  81. <input type="text" id="recipesearch">
  82. <button id="searchbutton">Search Me</button>
  83. <br>
  84. <input type="text" id="myingredients" placeholder="Enter Known Ingredients Here Seperated by a Comma"><br>
  85. <button id="submitknowningredients">Look for Recipes!</button>
  86. <button id="log">Log Me!</button>
  87. <script src="recipefinder.js"></script>
  88. </body>
  89. </html>
ymdaylpp

ymdaylpp1#

如果您只对设置容器元素的背景图像感兴趣(在本例中为document.body),就像上面的措辞一样,您可能会发现以下简短的使用片段。
您可以将事件侦听器绑定到file输入字段,并处理对文件选择所做的任何更改。事件处理程序可以访问files属性-有关File API的信息,请参阅here,并在应用程序中使用here。有趣的是,通过引用文件,FileReader api可以用于:阅读文件。
成功阅读文件后,FileReader示例将触发一个load事件,该事件触发一个回调函数,该函数用于创建一个新的Image,然后将其用作所选容器的backgroundImage属性。

  1. document.querySelector('input[type="file"]').addEventListener('change',e=>{
  2. let file=e.target.files[0];
  3. let reader = new FileReader();
  4. reader.onload=function( evt ){
  5. let img=new Image();
  6. img.onload=( e )=>{
  7. document.body.style.backgroundImage=`url(${img.src})`;
  8. /*
  9. To obtain a "storable" string representation of the image
  10. - write the image to a canvas and use `toDataURL` to get
  11. the base64 encoded source data....
  12. */
  13. let canvas=document.querySelector('canvas');
  14. canvas.width=img.width;
  15. canvas.height=img.height;
  16. let ctxt=canvas.getContext('2d');
  17. ctxt.drawImage( img, 0, 0 );
  18. let imgstr=canvas.toDataURL( file.type );
  19. ctxt.clearRect(0,0,ctxt.canvas.width,ctxt.canvas.height);
  20. console.log( imgstr )
  21. }
  22. img.src = evt.target.result;
  23. };
  24. reader.readAsDataURL( file );
  25. });
  1. canvas{display:none}
  1. <input type='file' />
  2. <canvas></canvas>

浏览本地系统上的图像文件以设置为背景图像。

展开查看全部

相关问题