Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

canvas 跨域问题

在微信上给用户修改头像的时候,用canvas来截图。结果报错:Owechat_login.js:226 Uncaught TypeError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The provided double value is non-finite.
代码:
function cropImage(targetCanvas, x, y, width, height) {

        var targetctx = targetCanvas.getContext('2d');
        var targetctxImageData = targetctx.getImageData(x, y, width, height); // sx, sy, sWidth, sHeight
    
        var c = document.createElement('canvas');
        var ctx = c.getContext('2d');
    
        c.width = width;
        c.height = height;
    
        ctx.rect(0, 0, width, height);
        ctx.fillStyle = 'white';
        ctx.fill();
        ctx.putImageData(targetctxImageData, 0, 0); // imageData, dx, dy
    
        document.getElementById('image').src = c.toDataURL('image/jpeg', 0.92);
        document.getElementById('image').style.display = 'initial';
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

初步看了下代码貌似没什么问题的,排除掉图片可能存在的跨域问题,还有一个问题楼主可以查看下就是getImageData 的传参,需要是number类型,楼主可以先使用

console.log(typeof x, typeof y, typeof width, typeof height)

来看看


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...