简体   繁体   中英

How do I put color into a rectangle in a canvas using a dropdown list onchange event

I have been trying to get the rectangle in the canvas to appear and try an fill it with color corresponding to the color on the drop down menu but i just cannot seem to get around it, any suggestions? (coursework) strong text

 window.onload = init; window.onload = myFunction; function init() { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.fillStyle = "white"; ctx.fillRect(20, 20, 10, 60); ctx.fillRect(70, 20, 10, 60); ctx.fillRect(120, 20, 10, 60); ctx.fillRect(170, 20, 10, 60); } function changeColor() { var eID = document.getElementById("colors"); var colorVal = eID.options[eID.selectedIndex].value; var colortxt = eID.options[eID.selectedIndex].text; document.getElementById('colorDiv').style.background = colortxt; } 
 <html> <head> <div id="content "> <center> <canvas id="colorDiv " width="300 " height="300 " style="border:1px solid #c3c3c3; "> </canvas> <select id="colors " onchange="changeColor() "> <option value="1 ">Black</option> <option value="2 ">Brown</option> <option value="3 ">Red</option> <option value="4 ">orange</option> <option value="5 ">Yellow</option> <option value="6 ">Blue</option> <option value="7 ">Violet</option> <option value="8 " selected="selected ">Grey</option> </select> </div> 

You've got multiple handlers here :

window.onload = init;
window.onload = myFunction;

your canvas id is colorDiv not mycanvas as you are using here :

var c = document.getElementById("myCanvas");

In all your ids and values you have a space appended. Use

<select id="colors" onchange="changeColor()">

instead of

<select id="colors " onchange="changeColor() ">

And make similar changes elsewhere.

Here's a working fiddle http://jsfiddle.net/p1bzeryt/4/

UPDATE

Change the selector id "myCanvas" to colorDiv as suggested by @Ramanlfc and use this function

function fillColor(color) {
  var c = document.getElementById("colorDiv");
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.fillStyle = color;
  ctx.fillRect(20, 20, 10, 60);
  ctx.fillRect(70, 20, 10, 60);
  ctx.fillRect(120, 20, 10, 60);
  ctx.fillRect(170, 20, 10, 60);
}

Working fiddle : http://jsfiddle.net/p1bzeryt/6/

You may call fillColor("white") onload, if you need to.

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