JavaScript onchange事件不适用于我的项目

时间:2016-08-23 16:27:11

标签: javascript canvas

我正在开发一个html画布项目,它允许用户修改输入字段,相应地更改球号图形。我的JavaScript工作正常,但onchange函数不会触发。我不知道为什么会这样。谁能帮我这个?非常感谢你的进步!

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Pyramid</title>
    <meta charset="utf-8" />
    <style>
        html{
            display: flex;
            justify-content: center;
        }
        canvas {
            border: 1px solid #333;
        }
    </style>
</head>
<body>
    <h1><strong>Pyramid</strong></h1>
    <canvas id="testCanvas"></canvas>
        <br />
    <h2>
    <label for="bandWidth">Row Numbers:</label>
    <input type="range" id="bandWidth" min="5" max="50"
           step="5" value="25"
           onchange= "init()">
    </h2>
    <script src="pyramid.js"></script>   
</body>
</html>

JavaScript的:

 window.onload = init;

        var canvas = document.getElementById('testCanvas');
        var NUM_ROWS = document.getElementById("bandWidth").value;

        //width = radius * 2 * number of rows
        canvas.width = NUM_ROWS * 10 * 2;
        canvas.height = NUM_ROWS * 10 * 2;
        var ballsLength = (NUM_ROWS + 1) * NUM_ROWS / 2;

        var ctx = canvas.getContext('2d');

        var balls = [];

        //create a Ball class
        var Ball = function () {
            this.x = 0;
            this.y = 0;
            this.radius = 10;
        };
      //create a public draw function
        Ball.prototype.draw = function (x, y, color) {
            this.x = x;
            this.y = y;
    //if color is true the fill color is red, otherwise the color is blue.
            if (color) {
                ctx.fillStyle = "red";
            } else {
                ctx.fillStyle = "blue";
            }
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
            ctx.fill();
            ctx.closePath();
        };

        function init() {
            for (var i = 0; i < ballsLength; i++) {
                balls.push(new Ball());
            }
            render();
        }

        function render() {
            var x, y, color;
            for (var i = NUM_ROWS; i >= 1 ; i--) {
                for (var j = 0; j < i; j++) {
                    color = i % 2;
                    x = j * balls[0].radius * 2 + (canvas.width / 2 + balls[0].radius) - i * balls[0].radius;
                    y = canvas.width - balls[0].radius - balls[0].radius * 2 * (NUM_ROWS - i);
                    balls[i].draw(x, y, color)
                    //console.log(x);
                    //console.log(y);
                }

            }

        }

0 个答案:

没有答案