2015-06-17 54 views
1

的裁剪當渲染以下圖像(右擊+查看圖片查看原圖):canvas.drawImage吹成像不成比例

http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png

大小4800x320使用HTML5 canvas.drawImage()

,並試圖作物從它的部分480x320圖像,畫布吹起的形象。

這裏是我的代碼:

var canvas = document.createElement('canvas'); 
canvas.setAttribute('id', 'my-canvas'); 
canvas.style.width = 480; 
canvas.style.height = 320; 
canvas.style.display = 'block'; 

document.body.appendChild(canvas); 

var img=document.createElement('img'); 
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png'; 
img.onload = function() { 
    var c=document.getElementById('my-canvas'); 
    var ctx=c.getContext('2d'); 
    ctx.drawImage(img,480,0,480,320,0,0,480,320); 
} 

此外,當我繪製圖像,以規模較小,它突然適合:

var canvas = document.createElement('canvas'); 
canvas.setAttribute('id', 'my-canvas'); 
canvas.style.width = 480; 
canvas.style.height = 320; 
canvas.style.display = 'block'; 

document.body.appendChild(canvas); 

var img=document.createElement('img'); 
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png'; 
img.onload = function() { 
    var c=document.getElementById('my-canvas'); 
    var ctx=c.getContext('2d'); 
    ctx.drawImage(img,480,0,480,320,0,0,240,160); 
} 

沒有人知道這是爲什麼?

回答

2

畫布'默認位圖大小爲300x150像素。設置CSS大小不會更改位圖大小。位圖直接在元素上設置自己的寬度/高度屬性/屬性。如果不是,位圖將被拉伸以填充CSS元素的大小。

更改這些:

canvas.style.width = 480; 
canvas.style.height = 320; 

canvas.width = 480; 
canvas.height = 320; 

您還可以設置你的代碼重用的背景:

//var c=document.getElementById('my-canvas'); // you already have this as canvas 
var ctx=canvas.getContext('2d');    // global/parent scope 

var img=document.createElement('img'); 
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png'; 
img.onload = function() { 
    ctx.drawImage(img,480,0,480,320,0,0,480,320); 
} 
+0

工作太棒了!非常感謝你! –

+0

@DrorHeller沒問題,很高興我能幫忙! :) – K3N