Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
How can a button press draw on canvas in javascript

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!