canvas to data url返回null

时间:2014-05-03 19:08:58

标签: canvas todataurl

有人可以向我解释为什么这个函数为变量dataURL _

返回null
function createsecondimage(dataURL,tempW,tempH,max_width,max_height,canvas){
var copy = document.createElement('canvas');
copy.width = max_width;
copy.height = max_height;
var copyctx = copy.getContext("2d");
var sx = (tempW - max_width) / 2
var sy = (tempH - max_height) /2
copyctx.fillStyle="#FFFFFF";
copyctx.fillRect(0,0,max_width,max_height); 
var imgcopy = new Image();
imgcopy.src = dataURL;
imgcopy.onload = function() {
copyctx.drawImage(imgcopy, sx, sy, 800, 800,0, 0, 800, 800);
var dataURL_ = copy.toDataURL("image/jpeg");

    }
 }

1 个答案:

答案 0 :(得分:0)

当我确保图像符合CORS以及我在imgcopy回调中的console.log(dataURL_)时,您的代码对我有用。

请记住,imgcopy.src将启动异步操作,因此不会立即填充dataURL_,而是保证在imgcopy.onload回调中加载。

此外,dataURL_仅在imgcopy.onload中可见,因为您在imgcopy.onload函数中执行了var dataURL_。 (你不是试图在onload之外访问dataURL_吗?)

无论如何......这是你的代码对我来说很好:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var img=new Image();
    img.crossOrigin="anonymous";
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png";
    function start(){
        ctx.drawImage(img,0,0);
        createsecondimage(canvas.toDataURL(),300,300,300,300,canvas);
    }


    function createsecondimage(dataURL,tempW,tempH,max_width,max_height,canvas){
        var copy = document.createElement('canvas');
        copy.width = max_width;
        copy.height = max_height;
        var copyctx = copy.getContext("2d");
        var sx = (tempW - max_width) / 2
        var sy = (tempH - max_height) /2
        copyctx.fillStyle="#FFFFFF";
        copyctx.fillRect(0,0,max_width,max_height); 
        var imgcopy = new Image();
        imgcopy.src = dataURL;
        imgcopy.onload = function() {
            copyctx.drawImage(imgcopy, sx, sy, 300, 300,0, 0, 300, 300);
            var dataURL_ = copy.toDataURL("image/jpeg");
            console.log(dataURL_);
        }
    }


}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>