Uploading an image to a Canvas using JavaScript?

2647 views 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;

var c = canvas.getContext('2d');


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>

  <meta charset="utf-8">

  <link href="styles.css" rel="stylesheet" type="text/css">


  <canvas class="canvas1">
  <!--<canvas class="canvas2">

  <script src="script.js"></script>




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


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


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?


Please login first before posting an answer.