画布图像在填充时重复而不是使用新图像

时间:2015-06-30 20:01:18

标签: jquery canvas

当我背靠背运行此代码时,通常它可以正常工作。但出于某种原因,它第二次被称为不改变画布图像......它使用相同的基础画布图像而我不知道为什么。

这里是小提琴: http://jsfiddle.net/wj2f9mhv/1/

这是代码:

.hidden = YES

//一件事确实有效...但我可以看到这可能失败的方法是在第二个函数周围设置超时:

//default values
var currentFill = "#cccccc";
var oldcolor = '';
var oldxImgToBeFilled = '';
var imgSection ;
var canvas;
var ctx;
var imgToBeFilled = new Image();
var imgFill = new Image();  
var xImgToBeFilled = new Array();
var xBlank = new Array();


xImgToBeFilled[1] =  "http://testing.treesclothing.com/images/canvas/top_slim_wrap_white.png";
xImgToBeFilled[6]  = "http://testing.treesclothing.com/images/canvas/skirt_knee_wrap_white.png";

function fillColorOrPattern(imgSection,currentFill){
   console.log('fillCOlorOrPattern imgSection:' +imgSection);


    imgToBeFilled = new Image();

    imgToBeFilled.onload = function () {
        //if ((oldcolor !== currentFill) || (oldxImgToBeFilled !== xImgToBeFilled[extractNumber(imgSection)])){
            fill(imgSection,currentFill);
        //}
    };


        imgToBeFilled.src = xImgToBeFilled[extractNumber(imgSection)];

    console.log('fillColorOrPattern imageToBeFilled: '+xImgToBeFilled[extractNumber(imgSection)]);
}



// fillColorOrPattern() -- fillColor()|| fillPattern() -- fill()
// last step 
function fill(imgSection,currentFill){
    console.log('fill imgSection:' + imgSection);
    canvas = document.getElementById(imgSection);
    ctx = canvas.getContext("2d");
    clear();

    ctx.drawImage(imgToBeFilled, 0, 0);
    ctx.globalCompositeOperation = "source-atop";   
    ctx.rect(0, 0, canvas.width, canvas.height);


     console.log(xImgToBeFilled[extractNumber(imgSection)]);


}

//gets the numerical step number from imgSection 
function extractNumber(varChar){
    return varChar.replace('s','').replace('image','');
}

//must clear canvas before adding any new color or pattern
function clear() {
    canvas.width = canvas.width;
}

//i also tried doing it this way
$.when(fillColorOrPattern('s1image',currentFill)).then(fillColorOrPattern('s6image',currentFill));

1 个答案:

答案 0 :(得分:1)

imgToBeFilled.onload中,将参考this发送给方法填充。喜欢这个

imgToBeFilled.onload = function () {
  fill(imgSection, currentFill, this); // <--- notice the 3rd parameter
};

在fill方法中使用对drawImage的引用。像这样的东西

function fill(imgSection, currentFill, img) {
    console.log('fill imgSection:' + imgSection);
    canvas = document.getElementById(imgSection);
    ctx = canvas.getContext("2d");
    clear();

    ctx.drawImage(img, 0, 0);
    ......
}

这是一个演示 http://jsfiddle.net/dhirajbodicherla/wj2f9mhv/2/