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

201
Views
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 answers
Answer question

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 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!