0

I need to populate a dropdown list with an array of color names. Below is the HTML and js codes I have, but when I actually press the drop-down, none of the colors show up and when I click the colors, the color of the canvas does not change. It also needs to have a button that clears the canvas when pressed. HTML

<!DOCTYPE html>
<html lang="en">
<head>
<title>Project 3</title>
<meta charset="utf-8">
<meta name="description" content="Project 3">
<meta name="author" content="Kim Peoples">
<link rel="stylesheet" href="p3.css">
<script src="p3.js"> </script>
</head>
<body>
<canvas width="500" height="500" id="myCanvas"></canvas>
<form id="myForm">
    <select id="colorDropdown">
        <option>Select a Background Color</option>
    </select>
</form>
<button onclick="clearCanvas">Clear Canvas</button>
</body>
</html>

JavaScript :

let selectElement = document.getElementById('#colorDropdown'),
let options = ["BlueViolet", "Crimson", "DarkSalmon", "OliveDrab", "SaddleBrown"];
for (let i < options.length - 1; i = 0; i++) {
    let opt = options[i];
    let optionList = document.createElement("option");
    optionList.textContent = opt;
    optionList.value = opt;
    select.appendChild(optionList)
}
document.getElementById('colorDropdown').onchange = function(){
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.fillStyle = document.getElementById('colorDropdown').value;

ctx.fill();
};

5 Answers5

1

It looks like you just had some syntax issues. I've copied your code to a JSFiddle, https://jsfiddle.net/wtvkv2t4/1/, and made the following changes:

  • Removed the let keyword from before the options variable name. You've used a comma at the end of the let selectElement ..... line, so you don't need to define options as a let, because it already is.
  • Changed the order of the parameters in the for loop condition
  • Replaced the use of a variable named select with the name of the variable that you actually defined, called selectElement

Here is the new, working code:

let selectElement = document.getElementById('colorDropdown'),
options = ["BlueViolet", "Crimson", "DarkSalmon", "OliveDrab", "SaddleBrown"];

for (let i = 0 ; i < options.length - 1; i++) {
  let opt = options[i];
  let optionList = document.createElement("option");
  optionList.textContent = opt;
  optionList.value = opt;
  selectElement.appendChild(optionList)
}

document.getElementById('colorDropdown').onchange = function() {
  let c = document.getElementById("myCanvas");
  let ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.rect(20, 20, 150, 100);
  ctx.fillStyle = document.getElementById('colorDropdown').value;

  ctx.fill();
};
Denno
  • 2,020
  • 3
  • 19
  • 27
  • For some reason it's still not showing up for me :( – Kim Peoples Dec 02 '17 at 03:26
  • I updated my answer with a third change that I had to make, which I forgot about.. It's the variable name for `select` and `selectElement`. Did you make that change too? Are you getting any errors on your console? – Denno Dec 02 '17 at 03:39
0

Your element name is selectElement but you populate options into select. There are errors in let selectElement = document.getElementById('#colorDropdown'), also. Another error is the order of the statements in the for loop. Please check the snippet for the corrected code.

var selectElement = document.getElementById("colorDropdown");
let options = ["BlueViolet", "Crimson", "DarkSalmon", "OliveDrab", "SaddleBrown"];
for (let i = 0; i < options.length - 1; i++) {
    let opt = options[i];
    let optionList = document.createElement("option");
    optionList.textContent = opt;
    optionList.value = opt;
    selectElement.appendChild(optionList)
}
document.getElementById('colorDropdown').onchange = function(){
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.fillStyle = document.getElementById('colorDropdown').value;

ctx.fill();
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Project 3</title>
<meta charset="utf-8">
<meta name="description" content="Project 3">
<meta name="author" content="Kim Peoples">
<link rel="stylesheet" href="p3.css">
<script src="p3.js"> </script>
</head>
<body>
<canvas width="500" height="500" id="myCanvas"></canvas>
<form id="myForm">
    <select id="colorDropdown">
        <option>Select a Background Color</option>
    </select>
</form>
<button onclick="clearCanvas">Clear Canvas</button>
</body>
</html>
Kavindra
  • 1,697
  • 2
  • 14
  • 19
  • { "message": "Uncaught ReferenceError: clearCanvas is not defined", "filename": "https://stacksnippets.net/js", "lineno": 28, "colno": 31 } – Mark Schultheiss Dec 02 '17 at 03:23
  • @MarkSchultheiss Well, I fixed the error with populating options in the dropdown. But I didn't implement the `clearCanvas` function. – Kavindra Dec 02 '17 at 03:27
0

you have error in your code :

for (let i < options.length - 1; i = 0; i++) this not right
-> for (let i=0 ; i < options.length; i++)

<button onclick="clearCanvas"> 

-> <button onclick="clearCanvas()">Clear Canvas</button>

i have write for you with right code.

<head>
<title>Project 3</title>
<meta charset="utf-8">
<meta name="description" content="Project 3">
<meta name="author" content="Kim Peoples">
<link rel="stylesheet" href="p3.css">
<script src="p3.js"> </script>
</head>
<body>
<canvas width="500" height="500" id="myCanvas"></canvas>
<form id="myForm">
    <select id="colorDropdown">
        <option>Select a Background Color</option>
    </select>
</form>
<button onclick="clearCanvas('#FFFFFF')">Clear Canvas</button>
<script>
    function init(){
        let selectElement = document.getElementById('colorDropdown');
        let options = ["BlueViolet", "Crimson", "DarkSalmon", "OliveDrab", "SaddleBrown"];

        for (let i=0 ; i < options.length; i++) {
            let optionList = document.createElement("option");
            optionList.innerHTML = options[i];
            optionList.value = options[i];
            selectElement.appendChild(optionList);
        }
    }
   init();
    document.getElementById('colorDropdown').onchange = function(){
     clearCanvas( this.value);
    };

   function clearCanvas(e) {
        let c = document.getElementById("myCanvas");
        let ctx = c.getContext("2d");
        ctx.beginPath();
        ctx.rect(20, 20, 150, 100);
        ctx.fillStyle = e;

        ctx.fill();
   }
</script>
</body>
</html>

I allowed myself to make some changes:
an function for initialize the select and i have combined the color change code whit the reset function.

bye

kiwi
  • 1
  • 2
  • Does setting the color to `#FFFFFF` actually "clear" it? – Mark Schultheiss Dec 02 '17 at 04:39
  • no, she recreated a white square. if your background is white the square this masked. – kiwi Dec 02 '17 at 04:56
  • if you need an realy clear -> save value of attributes, remove canvas, create an new, set Attribute and insert to last place ;) let c = document.getElementById("myCanvas"); let width = c.getAttribute ("width"); let height = c.getAttribute ("height"); let id = c.getAttribute ("id"); c.parentNode.removeChild(c); c = document.createElement("canvas"); c.setAttribute("width", width); c.setAttribute("height", height); c.setAttribute("id", id); let b=document.getElementById("myForm"); document.body.insertBefore(c,b); – kiwi Dec 02 '17 at 05:42
0

Added a clear function: reference that question. Small fixes and some comments

// probably should put this into a function so here....
window.onload = function () {
    let selectElement = document.getElementById('colorDropdown'),
      options = ["BlueViolet", "Crimson", "DarkSalmon", "OliveDrab", "SaddleBrown"];
    for (let i = 0; i < options.length - 1; i++) {
      let opt = options[i];
      let optionList = document.createElement("option");
      optionList.textContent = opt;
      optionList.value = opt;
      selectElement.appendChild(optionList)
    }
}
document.getElementById('colorDropdown').onchange = function() {
  let c = document.getElementById("myCanvas");
  let ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.rect(20, 20, 150, 100);
  ctx.fillStyle = document.getElementById('colorDropdown').value;
  ctx.fill();
};
// Leverage another question: https://stackoverflow.com/q/2142535/125981
document.getElementById('clearCanvas').onclick =
  function clearCanvas() {
    let canvas = document.getElementById("myCanvas");
    var context = canvas.getContext('2d');
    context.save();
    // Use the identity matrix while clearing the canvas
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0, canvas.width, canvas.height);
    // Restore the transform
    context.restore();
  }
<body>
  <canvas width="500" height="500" id="myCanvas"></canvas>
  <form id="myForm">
    <select id="colorDropdown">
        <option>Select a Background Color</option>
    </select>
  </form>
  <button id="clearCanvas">Clear Canvas</button>
</body>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
-2

This should work:

function update() {

  var color = ["undefined", "BlueViolet", "Crimson", "DarkSalmon", "OliveDrab", "SaddleBrown"];

  var y = document.getElementById("dropdown");
  var x = y.options[y.selectedIndex].value;

  document.getElementById("myCanvas").style = "background: " + color[x] + ";"

}
<body>
  <canvas width="500" height="500" id="myCanvas"></canvas>
  <br />
  <form>
    <select id="dropdown" onchange="update()">
   <option value="0">Select a Background Color</option>
   <option value="1">BlueViolet</option>
   <option value="2">Crimson</option>
   <option value="3">DarkSalmon</option>
   <option value="4">OliveDrab</option>
   <option value="5">SaddleBrown</option>
  </select>
    <input type="button" onclick="document.getElementById('dropdown').value = '0'; document.getElementById('myCanvas').style = 'background: undefined;'" value="Clear Canvas">
  </form>
  <br />
  <br />
  <br />
</body>

To add extra options, enter CSS color names, hex codes, or rgb codes to the var color array, as well as another <option> in the <select> menu, and set all the values to be consecutive integer, starting at 0 with the "Select a Background" option.


A Cleaner Alternative:

function update() {

  var y = document.getElementById("dropdown");
  var x = y.options[y.selectedIndex].innerHTML;

  document.getElementById("myCanvas").style = "background: " + x + ";"

}
<body>
  <canvas width="500" height="500" id="myCanvas"></canvas>
  <br />
  <form>
    <select id="dropdown" onchange="update()">
   <option value="0">Select a Background Color</option>
   <option>BlueViolet</option>
   <option>Crimson</option>
   <option>DarkSalmon</option>
   <option>OliveDrab</option>
   <option>SaddleBrown</option>
  </select>
    <input type="button" onclick="document.getElementById('dropdown').value = '0'; document.getElementById('myCanvas').style = 'background: undefined;'" value="Clear Canvas">
  </form>
  <br />
  <br />
  <br />
</body>


To add extra options, just add the CSS color name in between the option tags.


(Note: the <br /> tags are to add space between the at the bottom of the preview, so the stackoverflow console doesn't block the form. This shouldn't show up on a normal webpage.)

First Last
  • 45
  • 1
  • 6