canvas.toDataURL()生成错误的DataURL

时间:2013-08-11 10:19:57

标签: javascript html5 canvas html5-canvas data-uri

我的代码中toDataURL()函数的问题是什么!? 我的问题是,p0画布将保持为空! 在dataurl.net上传我的图像后,我发现,DataUrl代码和我在LocalStorage中保存的DataUrl代码是不同的!!这就是它无法展示的原因!

<canvas id="p0" width="512" height="176" style="margin-left: 200px; margin-top: 216px; position: absolute"></canvas>
<script>
function init() {
    var p0 = document.getElementById("p0");
    var P0 = p0.getContext('2d');
    var img = new Image;
    img.onload = function () {
        P0.drawImage(img, 0, 0);
    };
    if (localStorage.getItem("version") == Version) {
        img.src = localStorage.getItem("p0");
    } else {
        localStorage.setItem("version", Version);
        img.src = "Index/2/logo.png";
        localStorage.setItem("p0", p0.toDataURL("image/png"));
    }
}
init();
</script>

1 个答案:

答案 0 :(得分:2)

感谢Bergi,
它只需要把这一行:

localStorage.setItem("p0", p0.toDataURL("image/png"));

进入img.onload函数。

img.onload = function () {
    P0.drawImage(img, 0, 0);
    localStorage.setItem("p0", p0.toDataURL("image/png"));
};