简体   繁体   中英

Uploading an image to a Canvas using JavaScript?

I'm new to JS, but I'm currently trying to upload an image to an HTML canvas. There isn't a problem with the code, I just keep getting an error in the console that says: Failed to load resource: the server responded with a status of 404 (Not Found). In my IDE, it says that the image is there, but for some reason it's not showing on the preview. Any help would be appreciated!`

 var canvas = document.querySelector('.canvas1'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; //console.log(canvas); var c = canvas.getContext('2d'); load_image(); var base_image; function load_image() { "use strict"; base_image = new Image(); base_image.src = '\\Images\\trial.jpg'; base_image.onload = function() { c.drawImage(base_image, 0, 0); }; } 
 @charset "utf-8"; /* CSS Document */ body { margin: 0; } .canvas1 { height: 100vh; width: 98.7vw; margin: 0; display: block; } 
 <!doctype html> <html> <head> <meta charset="utf-8"> <title>Sylvanas</title> <link href="styles.css" rel="stylesheet" type="text/css"> </head> <body> <canvas class="canvas1"> </canvas> <!--<canvas class="canvas2"> </canvas>--> <script src="script.js"></script> </body> </html> 

`

You are putting the wrong path, [\\] in javascript escapes the next letter

 console.log('\\Images\\trial.jpg') 

so when you put path as "'\\Images\\trial.jpg'" it results in Images rial.jpg

You can either escape the path,use String.raw this my \\n really raw path or simply put the path in backticks [ like this ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM