0

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.

puzzleGuzzle
  • 101
  • 10
  • Everything is fine for me. Try to change id in HTML to lowercase `mycanvas`, so in JS. The problem is that your `canvas` not found by `getElementById` method. – Leonid Nov 02 '21 at 16:58
  • @Leonid Unfortunately, that does not work :( – puzzleGuzzle Nov 02 '21 at 20:06
  • We haven't got external scripts, so how can we help? Maybe they don't have access to DOM or window as global object, we don't know. Where exactly stimulus method plays and it what context? – Leonid Nov 02 '21 at 20:09
  • @Leonid I brought the problem up on a forum specialized for jsPsych (the JavaScript library I used) and it turns out that the script I was using was not conducive to running canvas elements. Thank you for your help! – puzzleGuzzle Nov 04 '21 at 02:46

0 Answers0