点击按钮再次启动我的画布

时间:2013-10-31 14:33:24

标签: javascript html canvas

我目前正在编写JavaScript,它会随机生成包含在我的表单框值中输入的框数的框,并使它们旋转等。

加载JavaScript时,我点击start()时生成的框是<input>标记中设置的默认值。如果我更改了脚本中的值并刷新了新的框数,那么如果我使用浏览器更改值并单击开始一个gizillion时间它只会刷新画布但是所有内容都保留在原位,换句话说,相同即使我减少或增加了数量,框也会出现在同一个地方:

<!DOCTYPE HTML>
<html>
<head><title>Rectangles</title></head>
<body>

<div id="rectangles" STYLE = "background-color: #fff68f; width: 600px; height: 420px; 
           border-style: outset;position: absolute;">
<form name="pGame">
<center>
<b>Canvas Application</b><br>
<input type= "button" value= "Start" onclick= "start()" />
<input id="box" type="text" size="2" value="20" style="border-style:inset;
             color:red; background-color: black" />
</center>
</form>
<script>

var shouldClear = 0;

这是我认为所有重置应该是:

  function start()
  {
    //tried making a counter, if its the first time to click save() context
    // else restore
    // context.restore(); but it didnt work, I think its because canvas and context 
    //arent declared here, but if I declare them in this scope or as global variable i get an error saying:Cannot call method 'getContext' of null 

  if (shouldClear<=0) {
   setInterval(rotateShape, 250);
   var degrees = 0.0;
   shouldClear += 1;
 }
if (shouldClear==1){
var canvas = document.getElementById('gameId');


    if (canvas.getContext) {
      var ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, 640, 480);
      for (i=0; i < allShapes.length; ++i) {
        allShapes[i].draw(ctx);
      }
      if (shouldClear==1) {
      ctx.clearRect(0, 0, 640, 480);
      construct();
      //shouldClear= shouldClear - 10;
      }
    }
}


}
 var chooseColor =0;
function construct()
 {

  var RotatingRectangle = function(x, y, width, height, rot, r,g,b){
    var rotation = rot;
    var rotationState = 0;
    this.draw = function(ctx){
      rotationState += rotation;

      ctx.save();
      ctx.translate(x+(width/2), y+(height/2));
      ctx.rotate(rotationState);

      var randomRed = Math.floor( Math.random() * 256 );
  var randomGreen = Math.floor( Math.random() * 256 );
  var randomBlue = Math.floor( Math.random() * 256 );
      ctx.fillStyle = "rgb(" + randomRed + ", " + randomGreen + ", " + randomBlue +")";
      ctx.fillRect(0-(width/2), 0-(height/2), width, height);
      ctx.restore();
    }
  }

   var count = parseInt(pGame.box.value);
    var allShapes = [];
    for (i=0; i < count; ++i) {
     if (chooseColor == 0) {

      var rotation = Math.random()*.10
      var x = Math.floor(Math.random() * 640);
      var y = Math.floor(Math.random() * 480);
      var randomRed = Math.floor( Math.random() * 256 );
    var randomGreen = Math.floor( Math.random() * 256 );
    var randomBlue = Math.floor( Math.random() * 256 );
      var rect = new RotatingRectangle(x, y, 15 + (Math.random() * 50), 15 + (Math.random() * 30), rotation, "rgb(" + randomRed + ", " + randomGreen + ", " + randomBlue +")");
      allShapes.push(rect); 
    }
    }
    chooseColor = 1;

    return allShapes;

}

var allShapes = construct();

 function rotateShape()
{
  var canvas = document.getElementById('gameId');


    if (canvas.getContext) {
      var ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, 640, 480);
      for (i=0; i < allShapes.length; ++i) {
        allShapes[i].draw(ctx);
      }
      if (shouldClear==1) {
      ctx.clearRect(0, 0, 640, 480);
      for (i=0; i < allShapes.length; ++i) {
        allShapes[i].draw(ctx);
      }
    }

    }
 }


  </script>
 <canvas id="gameId" width="598" height="300" 
    STYLE = "border:1px solid; background-color: #fff68f; position: absolute;">
 </canvas>
 <div style="font-size:12; position: relative; text-align: center; top: 320px;">
 Copyright &copy; 2005 <span style="font-family: cursive;">do it@knowHow</span></div>
 </div>
 </body>
 </html>

1 个答案:

答案 0 :(得分:1)

所以我发现重构你的代码比找到问题所在的更快。

现在工作正常,你可以在这里看到:

http://jsfiddle.net/gamealchemist/UW6eZ/

HTML:

<div id="rectangles" STYLE="background-color: #fff68f; width: 600px; height: 420px; 
           border-style: outset;position: absolute;">
    <form name="pGame">
        <center> <b>Canvas Application</b>

            <canvas id="gameId" width="598" height="300" style="border:1px solid; background-color: #eee68e; ">Your Browser does not support Canvas.</canvas>
            <br/>
            <input type="button" value="Start" onclick="updateShapes()"></input>
            <input id="box" type="text" size="2" value="20" style="border-style:inset;
             color:red; background-color: black"></input>
        </center>
    </form>
</div>

Javascript:
(如果在jsfiddle之外使用此代码,请务必等待加载的DOM)

// -------------------------------
// canvas and context
var canvas = document.getElementById('gameId');
var ctx = canvas.getContext('2d');


// -------------------------------
//  handle user input

function updateShapes() {
    allShapes = buildShapes(parseInt(pGame.box.value), canvas.width, canvas.height);
}
window.updateShapes = updateShapes;


// -------------------------------
//   Rotating rectangle Class 

function RotatingRectangle(x, y, width, height, rot, color) {
    this.x = x;
    this.y = y;
    this.rotation = rot;
    this.rotationState = 0;
    this.width = width;
    this.height = height;
    this.color = color;
}

RotatingRectangle.prototype.rotate = function () {
    this.rotationState += this.rotation;
};

RotatingRectangle.prototype.draw = function (ctx) {
    ctx.save();
    ctx.translate(this.x + (this.width / 2), this.y + (this.height / 2));
    ctx.rotate(this.rotationState);
    ctx.fillStyle = this.color;
    ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
    ctx.restore();
};


// -------------------------------
// handling a shape collection

// init
var allShapes = null;
updateShapes();

// build a set of random shapes
function buildShapes(count, maxX, maxY) {
    var tmpShapes = [];
    for (i = 0; i < count; ++i) {
        var rotation = 0.02 + Math.random() * .10
        var width = 15 + getRandom(50);
        var height = 15 + getRandom(30);
        var diag = Math.sqrt(width * width, height * height);
        var x = getRandom(maxX);
        var y = getRandom(maxY);
        if (x - diag < 0) x += diag;
        if (x + diag > maxX) x -= diag;
        if (y - diag < 0) y += diag;
        if (y + diag > maxY) y -= diag;
        var color = getRandomColor();
        var rect = new RotatingRectangle(x, y, width, height, rotation, color);
        tmpShapes.push(rect);
    }
    return tmpShapes;
}

// rotate all shapes
function rotateShapes() {
    for (i = 0; i < allShapes.length; i++) {
        allShapes[i].rotate();
    }
}

// draw all shpaes
function drawShapes(ctx) {
    ctx.clearRect(0, 0, 640, 480);
    for (i = 0; i < allShapes.length; i++) {
        allShapes[i].draw(ctx);
    }
}

// animate
polyFillRAFNow();

function animate() {
    requestAnimationFrame(animate);
    rotateShapes();
    drawShapes(ctx);
};

animate();


// -------------------------------
//   Helpers 

function getRandom(maxInt) {
    return 0 | Math.random() * maxInt;
}

function getRandomColor() {
    var color = 'rgb(' + getRandom(256) + ',' + getRandom(256) + ',' + getRandom(256) + ')';
    return normalizeColor(color);
}

function normalizeColor(colorString) {
    ctx.fillStyle = colorString;
    return ctx.fillStyle;
}

// requestAnimationFrame polyfill
function polyFillRAFNow() {
    var w = window,
        foundRequestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame || w.oRequestAnimationFrame || function (cb) {
            setTimeout(cb, 1000 / 60);
        };
    window.requestAnimationFrame = foundRequestAnimationFrame;
}