2017-04-21 97 views
0

當試圖使用context.drawImage()函數在畫布上繪製圖像而不是在畫布上顯示的完整圖像(兩者尺寸相同)時,它僅顯示縮放區域圖片。但是當我將圖像附加到DOM時,它顯示正確。你可以在jsfiddle中看到不同之處。頂部圖像是畫布,最下面的圖像是直接附加到文檔主體的圖像。在html canvas中繪製的圖像不是全尺寸的

https://jsfiddle.net/3fnq62nx/

而且,這裏是代碼片段,可能是什麼錯在這裏?

<html> 
<body> 
<canvas id="canvas" style="border: 1px solid black"> 
</canvas> 
<script type="text/javascript"> 
var canvas = document.getElementById("canvas"); 
var image = new Image(); 
image.src = "room_default.jpg"; 
image.height = "400"; 
image.width = "800"; 
image.onload = function(){ 
    canvas.width = image.width; 
    canvas.height = image.height; 
    document.body.appendChild(image); 
    var ctx= canvas.getContext("2d"); 
    ctx.drawImage(image,0,0); 
} 
</script> 
</body> 

+1

而不是'image.height =「400」; image.width =「800」;'write' image.style.height =「400px」; image.style.width =「800px」;' –

+0

@RolandStarke我嘗試過,但它將畫布大小設置爲圖像的原始尺寸1174x681。 –

回答

0

Here是您的解決方案

var canvas = document.getElementById("canvas"); 
var image = new Image(); 
image.src = "http://cdn.home-designing.com/wp-content/uploads/2011/06/livingroom_i_by_dragon2525-d3ioeyf.jpg"; 
image.height = "400"; 
image.width = "800"; 
image.onload = function(){ 
    canvas.width = image.width; 
    canvas.height = image.height; 
    document.body.appendChild(image); 
    var ctx= canvas.getContext("2d"); 
    ctx.drawImage(image,0,0,image.width,image.height); 
} 

更新ctx.drawImage(image,0,0,image.width,image.height);

您可以通過畫布圖像的情況下爲第4和drawImage方法的第5爭論的高度和寬度

+0

這是有效的!但我仍然沒有得到爲什麼我需要通過這些時調整大小的圖像和畫布是相同的尺寸。 –

0
hi please check this your issue resolvevar canvas = document.getElementById("canvas"); 
var image = new Image(); 
image.src = "http://cdn.home-designing.com/wp-content/uploads/2011/06/livingroom_i_by_dragon2525-d3ioeyf.jpg"; 
image.height = "400"; 
image.width = "800"; 
image.onload = function(){ 
    canvas.width = image.width; 
    canvas.height = image.height; 
    document.body.appendChild(image); 
    var ctx= canvas.getContext("2d"); 
    ctx.drawImage(image,0,0,image.width,image.height); 
}