繁体   English   中英

在JavaScript中使用for循环绘制Canvas的问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM