【问题标题】:canvas to data url return null画布到数据 url 返回 null
【发布时间】:2014-05-05 02:27:35
【问题描述】:

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

    }
 }

【问题讨论】:

  • 好吧,这个函数不返回任何东西。您是否打算返回(dataURL)?否则,您是否收到任何控制台错误? (1) 我看到函数缺少右括号。 (2) sx,sy 有效吗? (3) 图像是否至少为 800x800 - 否则您的 drawImage 将失败。 (4) 您是否因安全错误(CORS 合规性)而失败?
  • @markE 一切都正确传递,我可以将副本添加到 div 并查看调整大小的图像。由于某种原因,当我检查控制台时 dataURL_ 为空。

标签: canvas todataurl


【解决方案1】:

当我确保图像符合 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-11
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 2016-12-22
    • 2018-09-14
    • 2011-06-14
    相关资源
    最近更新 更多