[英]Problem with drawing Canvas using for loop in JavaScript
我無法在JavaScript中的for循環內的畫布中繪制矩形。 有時它們可見的時間只有一秒鍾,但它們會立即消失。 開發人員控制台中沒有錯誤-在Firefox和Chrome上進行了測試,因此問題與瀏覽器無關。 似乎只有我在班上遇到了這個問題,盡管代碼完全相同(或根據我的需要進行了稍微調整)。
代碼已在多個瀏覽器上進行了測試,該問題本身似乎僅在我的筆記本電腦/瀏覽器上發生-除了一些錯別字等,其他同事都沒有遇到此問題。
function Draw() {
var l = liczba.value; // user-input based loop control
var xpos = ypos = 300; // Left side rectangles starting drawing position
var xneg = 600, yneg = 300; // Right side rectangles starting drawing position
var canvas = document.getElementById('image');
var context = canvas.getContext('2d');
context.fillStyle = 'red';
for(var i = 0; i < l; i++) {
context.fillRect(xpos, ypos, 100, 100);
context.strokeRect(xpos, ypos, 100, 100);
console.log("Left Canvas Painted!"); // Debug
context.fillRect(xneg, yneg, 100, 100);
context.strokeRect(xneg, yneg, 100, 100);
console.log("Right Canvas Painted!"); // Debug
xpos += 50; xneg -= 50; ypos += 50; yneg += 50; // change next canvas' starting position by...
}
}
<body>
<form method="post" id="f" onsubmit="Draw();">
<label>Podaj liczbę figur do narysowania: </label>
<input type="text" name="liczba" id="liczba">
<input type="submit" name="send" id="send" value="Zatwierdź">
</form>
<canvas id="image" width="1200" height="800">Canvasy nie działają</canvas>
</body>
嘗試將按鈕從“提交”按鈕更改為普通按鈕,然后在click事件上調用Draw()。
<input type="button" onclick="Draw()" name="send" id="send" value="Zatwierdź">
感謝@jcbbdrn-這個問題的答案很簡單-我的一個小疏忽。 由於在提交表單時重新加載頁面,整個畫布都沖進了馬桶。 實現常規按鈕並為其分配onclick事件后,問題已解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.