1

谁能向我解释为什么这个函数为变量 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");

    }
 }
4

1 回答 1

0

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

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

此外, dataURL_ 仅在 imgcopy.onload 中可见,因为您var dataURL_在 imgcopy.onload 函数中进行了操作。(您不是试图在 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>
于 2014-05-04T18:22:02.417 回答