如何调整大小然后用画布裁剪图像 [英] How to resize then crop an image with canvas

查看:87
本文介绍了如何调整大小然后用画布裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道如何

- >调整图片大小:

-> resize an image:

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

- >或裁剪图片:

-> or crop an image:

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

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

But I don't know how to resize then crop an image. How could I do this? Thank you.

推荐答案

来自文档,这些是 drawImage的参数


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

因此,从源图像裁剪外部10个像素(假设它是 100 * 50 ),然后将其扩展到 160 * 60

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)

示例:

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

image.src = 'https://www.google.nl/images/srpr/logo3w.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: <br/>
<img src="https://www.google.nl/images/srpr/logo3w.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="275px" height="95px"></canvas>

这篇关于如何调整大小然后用画布裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆