简体   繁体   中英

Javascript onclick change the variable

I have here a piece of code and into my canvas it shows 10 triangles going into a circle but my problem is that the variable is 10 (var aantal = 10). I would like a dropdown menu where people can say how many triangles there have to rotate in the canvas.

here is how it looks like now: http://21248.hosts.ma-cloud.nl/bewijzenmap/periode4/SCT/10x3hoek/index.html

      var aantal = 10;
      var triangle = [];

      for (var i = 0; i < aantal; i++){
          triangle[i] = new Triangle;
          triangle[i].xLeft = 20 + 30*i;
          triangle[i].yLeft = 20 + 20*i;

      }

      (function drawFrame () {
         window.requestAnimationFrame(drawFrame, canvas);
         context.clearRect(0, 0, canvas.width, canvas.height);

       for (var i = 0; i < aantal; i++)

Add the following html to create a dropdown menu

<select id='aantal-select'>
  <option value='10'>10</option>
  <option value='20'>20</option>
  <option value='30'>30</option>
</select>

And then the following script to update your aantal variable

var selectElem = document.getElementById('aantal-select');

selectElem.onchange = function() {
    aantal = selectElem.value;

    var triangle = [];
    for (var i = 0; i < aantal; i++){
    triangle[i] = new Triangle;
        triangle[i].xLeft = 20 + 30*i;
        triangle[i].yLeft = 20 + 20*i;
    }
}

Add to your html

<select id="select_triangles">
   <option value="1">1</option>
   <option value="2" selected="selected">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select> 

In your javascript code you could check the value of the selected value like this

var e = document.getElementById("select_triangles");
var strUser = e.options[e.selectedIndex].value;

If you are using vanilla javascript (no Jquery/Angular or any other), the easiest will be to change the "aantal" variable to global (remove the "var" in the declaration). And to change this variable from another event (that the dropdown will initiate).

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