使用setTimeout的JavaScript循环数组运行到split undefined

时间:2014-12-03 17:04:03

标签: javascript

所以我有一个wordpress页面正在运行一个页面,让用户可以构建一个小漫画,生成3个代表漫画的图像。

用户可以自定义头发,眼睛,T恤等5个场景之间的选择,然后再根据场景的结果选择3个选项......

...最终的输出是3张图片,或者更确切地说是3张分层的png图像 - 分层的图像当然是选择的头发,眼睛,T恤等,以及任何情景选择的背景。< / p>

这个分层的图像集需要成为一个可共享的图像,所以我决定使用html2canvas渲染所有可能的图像,这些图像可以从1260的选择组合中创建。

我正在尝试预先生成所有这些图像,因为html2canvas对于实时使用来说有点冒犯,所以我试图以编程方式执行此操作。

图像生成贯穿我的1260种可能的组合阵列,直到大约一半我突然得到拆分未定义错误,我的代码首先输出所有1260个索引,所以我可以检查所有值都很好,一切似乎都没问题但我是真是难倒。

JS代码如下

// THIS 2D ARRAY IS A REPRESENTATION OF THE POSSIBLE VALUES A USER CAN CHOOSE PER HTML PANEL, AS A USER MAKES A CHOICE THE CURRENT PANEL HIDES AND REVEALS THE NEXT
var allArrays = [['0','1','2','3','4','5','6'], ['1','2'], ['0','1','2','3','4','5'], ['1','2','3','4','5'], ['1','2','3']];

// THIS FUNCTION BELOW USES RECURSION TO RUN THROUGH THE ABOVE ARRAY AND FIND ALL POSSIBLE UNIQUE COMBINATIONS A USER COULD SELECT OF WHICH THERE ARE 1260
function allPossibleCases(arr) {
    if (arr.length == 1) {
        return arr[0];
    } else {
        var result = [];
        var allCasesOfRest = allPossibleCases(arr.slice(1));
        for (var i = 0; i < allCasesOfRest.length; i++) {
            for (var j = 0; j < arr[0].length; j++) {
                result.push(arr[0][j] + " " + allCasesOfRest[i]);
            }
        }
        return result;
    }
}

// BEGIN THE RECURSION AND RETURN 2D ARRAY OF THE RESULTS
var uniqueIds = allPossibleCases(allArrays);

// THE BELOW FLATTENS THE RESULTING 2D ARRAY OUTPUT FROM THE 'allPossibleCases' FUNCTION TO A SINGLE ARRAY WITH ALL 1260
// EACH 1260 INDICES CONTAINS A UNIQUE COMBINATION OF THE NUMBERS BUT AS A STRING WITH SPACES e.g. "0 1 0 1 1", "1 1 0 1 1", "2 1 0 1 1"
var merged = [];
merged     = merged.concat.apply(merged, uniqueIds);

// OUTPUT THE FLATTEND ARRAY WITH ALL 1260 VALUES
console.log(merged);

var id1 = 0;
var id2 = 0;
var id3 = 0;
var id4 = 0;
var id5 = 0;

// INCREMENTATION VALUE FOR myTimer FUNCTION
var i   = 0;

// THE FUNCTION BELOW STEPS THROUGH EACH OF THE ARRAY ITEMS IN THE 'merged' ARRAY ALL 1260 USING i AS THE INCREMENTOR
function myTimer() {

    // FOR EACH INDEX IN THE ARRAY I NEED TO TAKE THE FIVE INDIVIDUAL STRING INTEGERS AND PUSH THEM INTO INDIVIDUAL 
    // TEXT INPUTS ON MY WEBSITES FRONTEND TO PROGRAMMATICALLY SIMULATE A USER HAVING GONE THROUGH AND MANUALLY MADE THESE CHOICES
    // I NEED TO USE JAVASCRIPT SPLIT TO PULL OUT EACH STRING INTEGER SO THAT I CAN USE IT ON MY FRONTEND AND ACHIEVE THIS USER FAKING
    var str = merged[i];
    console.log('Current render increment = '+i);
    console.log('The arrays current increment = '+str);
    var res = str.split(" ");

    // I CAST THE SPLIT STRING INTEGERS TO PROPER INTEGERS
    id1 = parseInt(res[0]);
    id2 = parseInt(res[1]);
    id3 = parseInt(res[2]);
    id4 = parseInt(res[3]);
    id5 = parseInt(res[4]);

    // NOW I PUSH EACH OF THESE VALUES INTO MY FORM TO FAKE A USER HAVING MADE ONE OF A POTENTIAL 1260 SET OF CHOICES
    $('.manualImageGen .hair').val(id1);
    $('.manualImageGen .eyes').val(id2);
    $('.manualImageGen .outfit').val(id3);
    $('.manualImageGen .scenario').val(id4);
    $('.manualImageGen .resolution').val(id5);

    // THIS LINE FORCES ANGULAR TO UPDATE ITS UI
    $('.manualImageGen input').trigger('input');

    // THIS IS USED TO TAG THE IMAGE GENERATED BY HTML2CANVAS WITH A UNIQUE ID RELATING TO ONE OF THE 1260
    var fileid = res[0]+res[1]+res[2]+res[3]+res[4];

    // HTML2CANVAS TAKES A SCREEN SHOT OF THE FINAL IMAGE GENERATED AS A RESULT OF FAKING THE CHOICES THAT WERE GENERATED
    html2canvas($('.finalImages'), {
        onrendered: function(canvas) {

            var data = canvas.toDataURL();

            $.ajax({
                type: "POST",
                url: ajaxurl,
                data: { 
                    'action':'nopriv_ra_addrelationstick',
                    'relStick' : data,
                    'fileid' : fileid
                }
            })
            .done(function( msg ) {
                if( msg == "false" )
                {
                    alert('Sorry but you need to log in to save your R Stick');
                }
            });

        }
    });

    if(i <= merged.length-1){
        i++;
        console.log("Items left to render = "+merged.length--);
    }else{
        clearInterval(myVar);
    }

}

// TRIGGER THE SETTIMEOUT LOOP ONCE PER SECOND TO STOP BROWSER FREEZING AND GIVE HTML2CANVAS TIME TO DO ITS THING
var myVar = setInterval(function () {myTimer()}, 1000);

1 个答案:

答案 0 :(得分:0)

万一你的域名中有这些图片,这是我的解决方案:

var layer0 = document.getElementById('input_layer0').value;
var layer1 = document.getElementById('input_layer1').value;
var layer2 = document.getElementById('input_layer2').value;
...
var panel = [layers[0][layer0],layers[1][layer1],layers[2][layer2]...];
var c = document.createElement('canvas').getContext('2d');
c.canvas.width = 200;
c.canvas.height = 200;
c.clearRect(0,0,200,200);
for(var i=0;i<panel.length;i++)
 c.drawImage(panel[i],0,0);
document.getElementById('result_image').src = c.canvas.toDataURL();

其中“layers”是不同图层的图像数组数组。

i = new Image();
i.src = 'bg1.jpg';
layers[0].push(i);
i = new Image();
i.src = 'bg2.jpg';
layers[0].push(i);
i = new Image();
i.src = 'body_sitting.png';
layers[1].push(i);
i = new Image();
i.src = 'body_standing.png';
layers[1].push(i);