2017-04-21 52 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); 
}