HTML5画布未显示完整图像

8

我的图片尺寸为940 * 300,但在Chrome中,html5画布只显示了部分图像。你能帮忙解决这个问题吗?

以下是代码:

<!DOCTYPE html>
<html>
    <head>
        <style></style>
    </head>
    <body onload="draw();">
        <p>Drag me</p>
        <canvas id="paint_area"></canvas>

        <script>
            function draw() {
                var ctx = document.getElementById('paint_area').getContext('2d');

                //ctx.fillStyle = '#cc3300';

                var img_buffer = document.createElement('img');
                img_buffer.src = 'http://www.jobcons.in/homebanner.jpg';
                var imgWidth = img_buffer.width;
                var imgHeight = img_buffer.height;
                ctx.width = imgWidth;
                ctx.height = imgHeight;
                ctx.drawImage(img_buffer,0,0,imgWidth,imgHeight);
            }
        </script>
    </body>
</html>
2个回答

10

两个问题:

  • 您正在设置上下文的大小,这没有太多意义。canvas有宽度和高度。

  • 您应该真正使用img_buffer.onload确保只有在图像加载完成之后才绘制图像,而不是在图像完全加载之前绘制。

示例:http://jsfiddle.net/pimvdb/TpFQ8/

所以:

<canvas id="paint_area" width="940" height="300"></canvas>

并且:

var cv  = document.getElementById('paint_area'),
    ctx = ctx.getContext('2d');

并且:

img_buffer.onload = function() {
    var imgWidth = img_buffer.width;
    var imgHeight = img_buffer.height;
    cv.width = imgWidth;
    cv.height = imgHeight;
    ctx.drawImage(img_buffer, 0, 0, imgWidth, imgHeight);
}

1
你需要将 ctx.width 改为 ctx.canvas.width - Phrogz
尽管画布有固定的初始宽度和高度(940x300)。那么在onload之后重置宽度和高度实际上是在做什么?我已经实现了这个逻辑。即使完整的图像现在显示出来了,但画布仍然是(940x300)。这背后的逻辑是什么?为什么画布的可见尺寸没有改变?我以为画布的宽度和高度会根据上传的图像而变化! - AL-zami

6
原因很简单,你无法做到。
  ctx.width= imgWidth;
  ctx.height=imgHeight;

您必须执行

  can.width= imgWidth;
  can.height=imgHeight;

这里的can是指canvas本身,而不是canvas上下文。

以下是工作示例:

http://jsfiddle.net/rbNzb/


1
请注意,您可以通过 ctx.canvas 从上下文中获取对画布的引用。 - Phrogz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接