Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda