2014-09-24 50 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