【问题标题】:Image drawn in html canvas is not full-sized在 html 画布中绘制的图像不是全尺寸的
【发布时间】:2017-04-21 16:30:02
【问题描述】:

当尝试使用 context.drawImage() 函数在画布上绘制图像时,而不是在画布上显示完整图像(两者大小相同),它仅显示图像的缩放区域。但是当我将图像附加到 DOM 时,它会正确显示。您可以在 jsfiddle 中看到差异。上图是画布,下图是直接附加到文档正文的图片。

https://jsfiddle.net/3fnq62nx/

这里还有代码 sn-p ,这里可能有什么问题?

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

【问题讨论】:

  • 而不是image.height = "400"; image.width = "800";image.style.height = "400px"; image.style.width = "800px";
  • @RolandStarke 我试过了,但是它将画布大小设置为图像的原始尺寸 1174x681。

标签: javascript html canvas


【解决方案1】:

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

您可以将画布图像事件的高度和宽度作为drawImage函数的第4个和第5个参数传递

【讨论】:

  • 行得通!但是当调整大小的图像和画布尺寸相同时,我仍然不明白为什么我需要传递那些。
【解决方案2】:
    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);
}

【讨论】:

    猜你喜欢
    • 2018-02-21
    • 2014-06-14
    • 1970-01-01
    • 2014-08-22
    • 2019-12-11
    • 2021-07-30
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    相关资源
    最近更新 更多