I am trying to implement the HTML canvas tag in Visual Studio Code, but it is not working.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="jspsych-6.3.1\jspsych.js"></script>
<script src="jspsych-6.3.1\plugins\jspsych-html-button-response.js"></script>
<link href="jspsych-6.3.1\css\jspsych.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
var finalTimeline = [];
var example = {
type: 'html-button-response',
stimulus: function() {
var c = document.getElementById("myCanvas");
var ctx= c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
}
};
finalTimeline.push(example);
jsPsych.init({
timeline: finalTimeline
});
</script>
</body>
</html>
When I try to run the code, I receive the following message in my debugger console: "Uncaught TypeError: Cannot read properties of null (reading 'getContext')."
I know that other people on this website have encountered the same problem, but after looking through some of their threads, it seems that their issue was that they had not added the canvas element to their DOM, i.e., they had not placed the element within the body tags. However, my canvas element is within the body tags, so I am not sure why my computer is not recognizing it.
Has anyone encountered this issue before? If so, would you please share your thoughts on resolving it?
Edit: The problem seems to be related to the fact that the canvas element is being called inside a jsPsych function. When I implement the code using regular JavaScript, it works fine.