2014-09-24 30 views
15

裁剪图像我已经知道如何如何调整,然后用帆布

- >调整图像大小:

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

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

回答

40

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) 

例子:

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>

+0

非常感谢您的回答。顺便说一句,我有一个小问题。裁剪后,如何调整“O”画布大小20x20? – Lewis 2014-09-24 13:30:45

+0

@Orion:实际画布(如在HTML元素中)?或者图像本身? – Cerbrus 2014-09-24 14:14:20

+0

我的意思是图像本身。我怎样才能调整它? – Lewis 2014-09-24 14:23:18