如何调整大小然后用画布裁剪图像

Lew*_*wis 24 javascript html5-canvas

我已经知道怎么做了

- >调整图像大小:

var image = document.getElementById('myImage'),
    canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');
ctx.drawImage(image,0,0,400,300);
Run Code Online (Sandbox Code Playgroud)

- >或裁剪图像:

var image = document.getElementById('myImage'),
    canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');
ctx.drawImage(image,50,50,image.width,image.height,0,0,50,50);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何调整大小然后裁剪图像.我怎么能这样做?谢谢.

Cer*_*rus 65

文档中,这些是以下参数drawImage:

drawImage(image,
    sx, sy, sw, sh,
    dx, dy, dw, dh);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

因此,要从源图像裁剪外部10个像素(假设它是100 * 50),然后将其缩放到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)
Run Code Online (Sandbox Code Playgroud)

例:

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)
}
Run Code Online (Sandbox Code Playgroud)
Image: <br/>
<img src="https://i.stack.imgur.com/I4jXc.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="275px" height="95px"></canvas>
Run Code Online (Sandbox Code Playgroud)


小智 5

在画布上绘制之前,使用 canvas.width 和 canvas.height 指定最终画布大小,否则最终将始终为 300x150