Uploading an image to a Canvas using JavaScript?

2647 views javascript
3

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>

`

answered question

Where do the backslashes come from to the image URL? You're actually trying to read the image from ImagesTABrial.jpg.

@Teemu see my answer its actually convertd to ` Images rial.jpg`

@AbhishekMathur \t is TABULATOR. And why to make a simple task complex? Just write the url using slashes as everybody else are doing ...

1 Answer

4

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.rawthis my \n really raw path or simply put the path in backticks [like this]

posted this

Have an answer?

JD

Please login first before posting an answer.