图像没有第一次绘制javascript

时间:2016-10-05 18:14:18

标签: javascript html5 canvas

我知道这个问题已被多次询问过。但是,我已经使用img.onload来正确执行加载图像后将绘制到画布的内容。我是javascript的新手,无法搞清楚。我已经在函数中完成了整个代码并从init()函数调用它。加载正文时会触发此init()函数。

我这里有两张照片。它们都不是第一次加载。

function getAboutMeImage(){
    var galleryCanvas = document.createElement("Canvas");
    var galleryContext = galleryCanvas.getContext('2d');
    galleryCanvas.width = 800;
    galleryCanvas.height = 600;
    galleryCanvas.style.position = "absolute";
    galleryCanvas.style.display = "block";
    galleryCanvas.style.top = "50%";
    galleryCanvas.style.left = "50%";
    galleryCanvas.style.marginLeft = "-400px";
    galleryCanvas.style.marginTop = "-250px";
    galleryCanvas.setAttribute("id","canvas2");
    //galleryCanvas.style.background = "#FFF";
    document.body.appendChild(galleryCanvas);

    var points = [];
    points[0] = new Array(0.3,1.3,0.55,1.05,2.9,1.05,3.1,0.75,9.25,0.75,9.9,1.3,9.9,6.3,9.6,6.6,5.75,6.6,5.3,7.0,2.5,7.0,1,4.3,0.3,4.3,0.3,1.3);
    var points1 = [];
    points1[0] = new Array(3.2,1,9.25,1,9.25,6.4,3.2,6.4,3.2,1);
    drawPoly(galleryCanvas.width,0,0,11.0,7.0,galleryCanvas,points,"rgba(194,242,227,.2)",'#c2f2e3',10);
    drawPoly(galleryCanvas.width,0,0,11.0,7.0,galleryCanvas,points1,"#000","#000",0);
    //debugCanvas(galleryCanvas);
    var y = Math.round((7.0 / 11.0) * galleryCanvas.width);
    var width = Math.round(galleryCanvas.width / 11.0);
    var height = Math.round(y / 7.0);
    var img = new Image();
    img.onload = function() {
        var canvas2 = document.getElementById("canvas2");
        var ctx2 = galleryCanvas.getContext("2d");
        ctx2.drawImage(img,0.4 * width, 1.2*height, img.width, img.height);
    };

    img.src = "../logo.png";
    var ratio = img.height * 1.0/ img.width;
    img.width = Math.round(width*2.7);
    img.height = Math.round(ratio * img.width);

    var img2 = new Image();
    img2.src = "../about me background2.png";
    var ratio = img2.height * 1.0/ img2.width;
    img2.width = Math.round(width*2.8);
    img2.height = Math.round(ratio * img.width);
    img2.onload = function(){
        var ctx3 = galleryCanvas.getContext("2d");
        ctx3.drawImage(img2,0.4 * width, 2*height, img2.width, img2.height);
    }

    setupAboutMe(galleryCanvas,galleryCanvas.width,20,0);

    return galleryCanvas.toDataURL();
}

那么,我做错了什么?

1 个答案:

答案 0 :(得分:1)

一般建议:

是否触发了onload回调?

如果没有,请检查图像.src

另外,请检查您要发送到drawImage的值。

结果x,y是否离开可见画布区域?

结果width,height是零还是接近零?