Home > Net >  Filling in a Canvas with different colours depending on the button pressed
Filling in a Canvas with different colours depending on the button pressed

Time:12-15

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()" >Blue</button>
        <button onclick="changered()" >Red</button>
        <button onclick="changegreen()" >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

CodePudding user response:

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()" >Blue</button>
<button onclick="changered()" >Red</button>
<button onclick="changegreen()" >Green</button>

  • Related