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

198
Vistas
Filling in a Canvas with different colours depending on the button pressed

I am attempting to create a simple interactive widget, where I want to fill in a canvas upon clicking a button. I have Blue, Red, Green with hexcodes listed. I have the functions listed, and the fill listed but it doesn't change anything when I click the buttons.

//HTML

        <form>
        <canvas id="canvas" width="500" height="300"></canvas>
        <button onclick="changeblue()" class="canbut">Blue</button>
        <button onclick="changered()" class="canbut">Red</button>
        <button onclick="changegreen()" class="canbut">Green</button>
        </form>

//Js

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

function changeblue (){
  ctx.fillStyle = "#0066FF";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function changered(){
ctx.fillStyle ="#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function changegreen (){
ctx.fillStyle ="#00cc00";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You have to remove the form tag, or add a preventDefault to your JS code

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

function changeblue(e) {
  ctx.fillStyle = "#0066FF";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function changered() {
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function changegreen() {
  ctx.fillStyle = "#00cc00";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}
<canvas id="canvas" width="500" height="300" style="border:2px solid black"></canvas>
<button onclick="changeblue()" class="canbut">Blue</button>
<button onclick="changered()" class="canbut">Red</button>
<button onclick="changegreen()" class="canbut">Green</button>

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