Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda