Image crop after rotate by canvas

前端 未结 3 995
庸人自扰
庸人自扰 2020-12-09 14:10

I have a html5 canvas. I want to draw/rotate the image in the canvas and image size does not change.I set width/height of canvas base on size of image.I have a problem to r

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 14:46

    Issues

    There are two issues you are facing:

    1. There is not enough room in the canvas to do a rotation
    2. You are drawing the image at center of rotation rather than center of image

    Solutions

    To properly size your canvas you can use maximum boundary of the rotated rectangle. To find this boundary you can do one of two things:

    If you only need to rotate per 90 degrees:

    var length = Math.max(img.width, img.height);
    

    If you want to use free angle:

    var length = Math.sqrt(img.width * img.width + img.height * img.height);
    

    Then use one of these results to set the size of the canvas:

    canvas.width = canvas.height = length; /// both has same length
    

    Next thing is to properly draw in the image. After rotation you need to translate back as the image is always drawn from its upper left corner:

    var pivot = length * 0.5;
    
    ctx.save();
    ctx.translate(pivot, pivot);
    ctx.rotate(degrees * Math.PI / 180);
    ctx.drawImage(image, -image.width * 0.5, -image.height * 0.5);
    ctx.restore();
    

    It's important you use the pivot of the image to offset it back as the image will here be of a different size than canvas.

    The result from this LIVE DEMO here:

    Bounds of rotated rectangle

提交回复
热议问题