帆布颜色“漏水”

时间:2016-01-30 13:27:12

标签: javascript canvas

我正在制作一个为你制作方格画布的程序,你可以在页面底部找到它。

它看起来不错但是当你选择一个有大量线条的大尺寸时,它会开始出现泄漏或类似的东西。例如,尝试用三行选择大小二十。你明白我的意思。

如果您打开控制台我console.log - 编辑颜色编号的值和正在绘制的颜色。

以下是JSfiddle和相关函数的链接: https://jsfiddle.net/6r05ye2t/

function make() {
            var canvas = document.getElementById("canvas").getContext("2d");
            var linelength = 1;
            var colors = [], inputs = document.getElementsByClassName("color");
            for (var j = 0; j < lines; j++) {
                colors.push(inputs[j].value);
            }
            console.log(size);
            var colornum = 0, shift = 0;
            for (var column = 0; column < size; column++) {
                for (var row = 0; row < size; row++) {
                    if (colornum >= lines) {
                        colornum -= lines;
                    }
                    canvas.fillStyle = colors[colornum];console.log(colornum);console.log(colors[colornum]);
                    colornum++;
                    canvas.fillRect(row*50, column*50, 50, 50);
                }
                shift++;
                colornum = shift;
            }
        }

1 个答案:

答案 0 :(得分:0)

我猜是因为我不确定你的意思&#34; Leak&#34;?

按如下方式更改渲染循环

for (var column = 0; column < size; column += 1) {
    for (var row = 0; row < size; row += 1) {
        // remove the condition statement
        //if (colornum >= lines) {  // remove
        //  colornum -= lines;      // remove
        //}                         // remove

        // Then to get the values 0, 1, 2, ... (lines-1)
        // use the modulo operator % to get the remainder of colornum divided 
        // by lines. 

        canvas.fillStyle = colors[colornum % lines];
        canvas.fillRect(row * 50, column * 50, 50, 50);
        colornum += 1;
    }
    shift += 1;
    colornum = shift;
}