2013-10-31 27 views
1

我目前編寫JavaScript會隨機地在我的表格框的值inputed箱數生成箱的過程中,並使其旋轉等另起爐竈我的畫布上的按鈕,點擊

當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 [email protected]</span></div> 
</div> 
</body> 
</html> 
+0

clearRect ();可能有助於清除畫布 –

+0

clearRect()只會從畫布中移除當前對象,但不會爲矩形或它們的位置重新生成新值,並在清除的畫布上繪製()它們。 –

+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; 
} 
+0

謝謝你,「GameAlchemist」,我能夠睡覺tongiht :) ..它只是awsome你如何管理它,希望你不介意,生病通過你的代碼和研究一段時間,並可能會問幾個問題..再次,謝謝百萬 –

+0

不客氣!很高興我能確保你有一個美好的夜晚:-)是的,在你弄清楚我做出的改變(基本上是重構)之後,請毫不猶豫地詢問精度。 – GameAlchemist