使用图像组合画布在Android上运行但在IOS上无声地失败

时间:2015-09-21 23:33:56

标签: android ios cordova canvas

我有以下代码在IOS上失败,但适用于Android (using ionic/cordova)。我错过了什么(也许我对Android很幸运!)?在机器人上我得到了图像的无缝垂直堆叠,而在IOS上,我得到一个空白的外观。它在IOS上失败,无论我是堆叠一个SVG还是多个。

SVG元素本身在页面上显示正常,在debugger我可以看到他们的完整标记。

function _appendImgToCanvas(canvas, image, first_image) {
    // image contents are -- {id, h, w}
    var ctx = canvas.getContext("2d");
    var img_type = "data:image/svg+xml;charset=utf-8";
    try {
        var img_el = document.getElementById(image.id).getElementsByTagName("svg")[0];
        var img_src = new XMLSerializer().serializeToString(img_el); // thx Kaiido
        var img = new Image();
        img.src = img_type + "," + img_src;
        var h = image.h, w = image.w; // is in CSS pixels
        var old_h = canvas.height, old_w = canvas.width;
        var old_image;
        if (first_image) {
            ctx.clearRect(0, 0, old_w, old_h);
            old_h = old_w = 0; // it's a new beginning
        } else {
            old_image = canvas.toDataURL("image/png"); // Android appears to wipe out image on resizing
        }
        // update canvas dims, and update its CSS style too
        canvas.setAttribute("height", old_h + h);
        canvas.setAttribute("width", Math.max(w, old_w));
        canvas.style.height = canvas.height + "px";
        canvas.style.width = canvas.width + "px";
        // retrieve any old image into the resized canvas
        if (old_image) {
            var x = new Image();
            x.src = old_image;
            ctx.drawImage(x,0,0);
        }
        // add the given image
        ctx.drawImage(img, 0, old_h);
        $log.debug("IMG#" + image.id, w,"x",h, "appended at h=", old_h, "new dim=", canvas.width, "x", canvas.height);
    } catch(e){$log.error("IMG#" + image.id, "ERROR in appending", e);
            }
}

1 个答案:

答案 0 :(得分:0)

您必须等待已加载的图片,将绘图操作添加到他们的onload处理程序中。

另外,要将svg元素转换为dataURL,请使用encodeURIComponent(new XMLSerializer().serializeToString(yourSVGElement))方法而不是outerHTML / innerHTML,这样可以避免编码问题和if/else //probably ios..