简体   繁体   中英

Problem with drawing Canvas using for loop in JavaScript

I am unable to draw rectangles in canvas within for loop in JavaScript. Sometimes they are visible for a fraction of second, but they disappear instantly. No errors in developer console - tested on Firefox & Chrome, so problem isn't browser-related. Seems like only I encountered this issue within my class, despite having exactly the same (or slightly adjusted to my needs) code.

Code was tested on multiple browsers, the problem itself seems to occur only on my laptop/browser - rest of my colleagues haven't encountered this issue, apart from some typos etc.

The general idea is to receive a result similar to this one: 在此处输入图片说明

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ź">

The answer to this issue was pretty straight-forward, thanks to @jcbbdrn - a minor oversight on my part. Due to page reload on form submitting, whole canvas was flushed down the toilet. After implementing a regular button and assigning to it an onclick event, the problem has been solved.

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