canvas drawImage onload函数不起作用

时间:2014-11-25 12:28:49

标签: javascript svg

在这段代码中,我从svg元素中获取了base64值。因为我想要png / jpg值来从画布创建图像,但它不能正常运行图像onload函数。

<script>
    jQuery(document).ready(function() {
    var svgData = document.getElementById("svgdiv").innerHTML;
    var url = "data:image/svg+xml;base64," + btoa(svgData);
    getBase64FromImageUrl(url);
    });
    function getBase64FromImageUrl(URL) {
    var img = new Image();
    img.src = URL;
    console.log(img);

    img.onload = function() {// here code not working
        console.log("FDF");
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));

    };
    }
</script>

1 个答案:

答案 0 :(得分:2)

正如我在评论中所说,您需要在 之后指定.src img属性onload处理程序。删除console.log电话仍然无法执行此操作。当然,它确实减少了分配src和分配onload处理程序之间的时间,但这不是实现它的方法。

这里的代码包含了所需的额外内容,使其成为一个功能齐全的示例。请注意作业的顺序和console.log来电。

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}

function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}

function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    var svgData = byId("svgdiv").innerHTML;
    var url = "data:image/svg+xml;base64," + btoa(svgData);
    getBase64FromImageUrl(url);
}

function getBase64FromImageUrl(URL) 
{
    var img = new Image();
    document.body.appendChild(img);

    // here code not working
    img.onload = function() 
    {
        console.log("FDF");
        var canvas = newEl("canvas");
        canvas.width = this.width;
        canvas.height = this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
    };

    img.src = URL;
    console.log(img);
}

</script>
<style>
</style>
</head>
<body>
    <div id='svgdiv'>
        <svg id="svgRoot" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <rect x="0" y="0" width="100%" height="100%" fill="#009399"/>
        <circle cx="150" cy="75" r="50" fill="blue" onmouseover="this.setAttribute('fill', 'white')" onmouseout="this.setAttribute('fill', 'blue')"/>
        </svg>
    </div>
</body>
</html>