0

I'm trying to draw a rectangle when the user presses a button in Javascript. If the code in the script is not in a function, it draws the rectangle but of course doesn't respond to the button. If I put it in a function called by the button, nothing happens whether it's in the head or the body. How can I draw the rectangle with the button press?

Many thanks in advance!

<html>
<head>
    <title>Test 4</title>

    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>

<body>
    <canvas id="myCanvas" width="400" height="600">
        <p>Fallback content for browsers that don't support the canvas tag.</p>
    </canvas>

    <script>
        function myFunction() {
            const canvas = document.querySelector('.myCanvas');
            const width = canvas.width = window.innerWidth;
            const height = canvas.height = window.innerHeight;
            const ctx = canvas.getContext('2d');

            ctx.fillStyle = 'rgb(255, 255, 255)';
            ctx.fillRect(0, 0, width, height);

            ctx.fillStyle = 'rgb(255, 0, 0)';
            ctx.fillRect(50, 50, 100, 150);
        }
    </script>

    <p>
        Click the button
        <button onclick="myFunction()">Try it</button>
    </p>

</body>
</html>

1 Answer 1

1

Change your query selector to #myCanvas.

A prefix of . indicates it should find an element with a class of myCanvas, to search instead for an element id use the # prefix.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.