javascript - 如何使用 Canvas 调整图像大小然后裁剪图像

标签 javascript html5-canvas

我已经知道如何

-> 调整图像大小:

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

-> 或裁剪图像:

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);

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

最佳答案

来自documentation ,这些是 drawImage 的参数:

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

enter image description here

因此,要从源图像中裁剪外部 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)

示例:

const image = new Image(),
      canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d');

image.src = '/image/I4jXc.png';

image.addEventListener('load', () => {
    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: <br/>
<img src="/image/I4jXc.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="275px" height="95px"></canvas>

关于javascript - 如何使用 Canvas 调整图像大小然后裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26015497/

相关文章:

javascript - Javascript Falling Rocks 游戏中的碰撞检测

javascript - 将属性保留到 Express 中的以下中间件

javascript - 如何用 2 个 SVG 制作自定义进度条?使用 Canvas ?

javaScript多次图像未加载

javascript - 立即使用 AngularJS 从 Firebase 加载数据

javascript - 发射器跟随 Canvas 中的粒子

javascript - fabric.js 中带有路径的错误边界框

javascript - node.js 返回未定义的问题

javascript - js语法区别

javascript - Chrome 应用程序中的按钮不起作用