-2

I'm afraid this might be a totally sophomoric question but I've truly run out of ideas here so please bear with me. I have used html and css in the past to build websites but I am totally new to implementing javascript. I have found code I want to use online but when I use it there is an error on the javascript file telling me that c is undefined. I don't understand why this is because my css stylesheet can use c (which is defined in the html file) just fine, and the javascript file is linked correctly (to the best of my knowledge) to the html file.

The error is in reference to the first line of the javascript file and it says: Uncaught ReferenceError: c is not defined. Could somebody please show me what I'm doing wrong???

It is supposed to produce a wiping effect between two images. Here's all my code:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <title>Home</title>
  <link media="screen" rel="stylesheet" href="index.css" type="text/css">
  <script type="text/javascript" src="jquery-3.3.1.js"></script>
  <script src="index.js"></script>

</head>

<body>

  <canvas id=c width=620 height=400></canvas>

</body>

</html>

CSS:

#c {
  background: url(https://i.imgur.com/db03ziu.jpg); 
  background-size: cover;
}

Javascript:

var ctx = c.getContext("2d"),
img = new Image();         // image to show

img.onload = start;
img.src = "https://i.imgur.com/caE9x1j.jpg";

function start() {
  c.onmousemove = function(e) {
  var r = c.getBoundingClientRect(),
  x = e.clientX - r.left;
  ctx.clearRect(0, 0, c.width, c.height); 
  ctx.drawImage(img, 0, 0, x, c.height,  0, 0, x, c.height); 
  ctx.fillRect(x, 0, 5, c.height); 
  };

}
Eoin Coffey
  • 11
  • 1
  • 2
  • 2
    Your element does not exist yet. – SLaks Apr 11 '18 at 15:52
  • Using `getElementById()` won't work either. The ` – Pointy Apr 11 '18 at 15:53
  • Please refer [Canvas HTML](https://www.w3schools.com/html/html5_canvas.asp). Your problem maybe come from . Please change from id=c to id="C" as – Hai Dinh Apr 11 '18 at 17:08

1 Answers1

1

You get the error because you haven't defined c yet. Add:

let c = document.getElementById('c');

to the top of the JS file.

You might also need to move the script include to the bottom of the HTML file (just before </body>) because when the JS file loads, the DOM might not have loaded so the element might still not exist.

Do DOM tree elements with ids become global variables? might be an interesting read, but you should just define it outright.

ᔕᖺᘎᕊ
  • 2,971
  • 3
  • 23
  • 38