【问题标题】:html5 canvas is not showing full imagehtml5 画布未显示完整图像
【发布时间】:2017-10-03 18:17:06
【问题描述】:

我的图像大小是 940 * 300,但 html5 画布仅显示 chrome 中图像的一部分。你能帮忙解决这个问题吗?

下面是代码

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

【问题讨论】:

    标签: html canvas html5-canvas


    【解决方案1】:

    两件事:

    • 您设置的上下文大小没有多大意义。 画布有一个宽度和一个高度。

    • 您确实应该使用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);
    }
    

    【讨论】:

    • 你需要把ctx.width改成ctx.canvas.width
    • 即使画布具有固定的初始宽度和高度(940x300)。那么为什么实际上在 onload 之后重置宽度和高度呢?我已经实现了这个逻辑。现在甚至显示完整的图像,但画布仍然是(940x300)。这背后的逻辑是什么。为什么画布可见尺寸没有改变?我认为画布的宽度和高度会根据上传的图像而有所不同!
    【解决方案2】:

    原因很简单,你不能

      ctx.width= imgWidth;
      ctx.height=imgHeight;
    

    你必须这样做

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

    其中can 是对画布的引用,不是画布上下文。

    工作示例:

    http://jsfiddle.net/rbNzb/

    【讨论】:

    • 请注意,您可以使用 ctx.canvas 从上下文中获取对画布的引用。
    猜你喜欢
    • 2012-03-21
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 2014-03-23
    • 2011-05-09
    相关资源
    最近更新 更多