Cropping with drawImage not working in Safari

后端 未结 1 663
有刺的猬
有刺的猬 2020-12-11 02:44

I\'m working on some simple image manipulation functions with canvas. The user uploads an image, is able to rotate and crop it and then clicks ok. The image is then split in

相关标签:
1条回答
  • 2020-12-11 03:42

    The bug occurs when drawImage() is called out of the bounds of the sourceImage.

    You have to double check that the source width and source height are always smaller or equal to the image's width and height :

    So for the first if block :

    var sourceX = image.width/2;
    var sourceY = 0;
    var sourceWidth = image.width - sourceX; // you're in the bounds
    var sourceHeight = image.height;
    var destX = canvas.width/2;
    var destY = 0;
    var destWidth = canvas.width;
    var destHeight = canvas.height;
    
    ctx.drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
    

    Or as a one-liner :

    ctx.drawImage(image, image.width/2, 0, image.width - (image.width/2), image.height, canvas.width/2, 0, canvas.width, canvas.height);
    
    0 讨论(0)
提交回复
热议问题