2014-09-24 11 views
15

już wiem jakJak zmienić rozmiar następnie przyciąć obraz z płótna

-> zmienić rozmiar obrazu:

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

-> lub przyciąć obraz:

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

Ale nie wiem jak zmienić rozmiar, a następnie przyciąć obraz. Jak mogłem to zrobić? Dziękuję Ci.

Odpowiedz

40

Z documentation, są to parametry dla drawImage:

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

enter image description here

Tak więc, aby przyciąć zewnętrzne 10 pikseli z obrazu źródłowego (Zakładając, że to 100 * 50) oraz następnie przeskaluj aż do 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) 

Przykład:

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

Wielkie dzięki za odpowiedź. BTW, mam małe pytanie. Jak zmienić rozmiar płótna 'O' na rozmiar 20x20 po przycięciu? – Lewis

+0

@Orion: rzeczywiste płótno (jak w elemencie HTML)? A może sam obraz? – Cerbrus

+0

Mam na myśli sam obraz. Jak mogę zmienić rozmiar? – Lewis

Powiązane problemy