How to resize then crop an image with canvas

后端 未结 3 1981
一向
一向 2020-11-28 07:17

I already know how to

-> resize an image:

var image = document.getElementById(\'myImage\'),
    canvas = document.createElement(\'canvas\'),
    ctx          


        
3条回答
  •  广开言路
    2020-11-28 07:29

    From the documentation, these are the parameters for drawImage:

    drawImage(image,
        sx, sy, sw, sh,
        dx, dy, dw, dh);
    

    enter image description here

    So, to crop the outer 10 pixels from the source image (Assuming it's 100 * 50), and then to scale that up to 160*60:

    ctx.drawImage(image,
        10, 10,   // Start at 10 pixels from the left and the top of the image (crop),
        80, 30,   // "Get" a `80 * 30` (w * h) area from the source image (crop),
        0, 0,     // Place the result at 0, 0 in the canvas,
        160, 60); // With as width / height: 160 * 60 (scale)
    

    Example:

    var image = new Image(),
        canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d');
    
    image.src = 'https://i.stack.imgur.com/I4jXc.png';
    
    image.onload = function(){
        ctx.drawImage(image,
            70, 20,   // Start at 70/20 pixels from the left and the top of the image (crop),
            50, 50,   // "Get" a `50 * 50` (w * h) area from the source image (crop),
            0, 0,     // Place the result at 0, 0 in the canvas,
            100, 100); // With as width / height: 100 * 100 (scale)
    }
    Image: 

    Canvas:

提交回复
热议问题