简体   繁体   中英

How to fill a canvas with a select color?

I'm trying to fill a rectangle canvas with some colors from a dropbox. Right now, I'm trying to fill the canvas with: white, red, blue, green. When click in the button Add color show fill the canvas with the selected color. When click Clear Button, should reset/remove the color.

So far my html code is:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="colors.js" type="text/javascript" defer></script>
  </head>

  <body onload="setUp()">
    <h1>Canvas colors</h1>

     <p>What colors should fill?
       <select>
        <option value="white">White</option>
        <option value="red">Red</option>
        <option value="blue">Blue</option>
        <option value="green">Green</option>
       </select>
     <button type="button" id="addColor" name="button">Add Color</button>
     <button type="button" id="clearColor" name="button">Clear Color</button>
    </p>

    <br>
    <br>

    <canvas id="myCanvas" height="300" width="300" style="border: 1px solid black"></canvas>

  </body>
</html>

JS:

let canvas;
let ctx;

function setUp(){
   canvas = document.getElementById("myCanvas");
   ctx = canvas.getContext("2d");
   let addColor = document.getElementById('addColor');
   let clearColor = document.getElementById('clearColor');
   myCanvas();

}

addColor.onclick = function() {
  function myCanvas(){
  ctx.fillStyle = ["white", "red", "blue", "green", "pink", "purple", "black", "orange"];
  ctx.fillRect(0, 0, canvas.width, canvas.height);
 }
}

clearColor.onclick = function() {
  function myCanvas(){
    ctx.fillStyle = white;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
   }
}

Your JS code is totally wrong.

Here is a working example

Your mistake is that you are adding event handlers to elements (variables) addColor and clearColor declared inside setUp function closure.

In your case, the JS-code should look like this:

function setUp(){
    let canvas = document.getElementById("myCanvas");
    let ctx = canvas.getContext("2d");
    document.getElementById('addColor').onclick = function() {
      ctx.fillStyle =  document.getElementById('colorSelector').value;
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    };

    document.getElementById('clearColor').onclick = function() {
      ctx.fillStyle = 'white';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM