画布中的图像高度错误

时间:2012-05-02 15:13:13

标签: javascript html5 canvas

我有这样的画布

<canvas id="canvas" width="600px" height="300px"></canvas>

现在我试图在宽度和高度为260px的画布内显示图像。但它显示的图像在画布上完全放映。我做错了什么?

img.onload = function(){
                var im = this;
                var imgWidth = im.width;
                var imgHeight = im.height;

                var imgScaledWidth = 0;
                var imgScaledHeight = 0;

                imgScaledHeight = self.conHeight - 40;
                imgScaledWidth = imgScaledHeight * (imgWidth/imgHeight);

                self.context.drawImage(this, 0,0,imgScaledWidth,imgScaledHeight);
            }

它的表现如此 enter image description here

2 个答案:

答案 0 :(得分:1)

根据您在问题中显示的内容,您的代码无法正常运行。 Here is an example根据您提供的代码进行一些细微更改,以说明没有self变量。

<script>
    var img = document.getElementById("image");
    var c = document.getElementById("canvas");
    var con = c.getContext("2d");

    img.onload = function(){
        var im = this;
        var imgWidth = im.width;
        var imgHeight = im.height;

        var imgScaledWidth = 0;
        var imgScaledHeight = 0;
        var off=20;            

        imgScaledHeight = c.height - off;
        imgScaledWidth = imgScaledHeight * (imgWidth/imgHeight);

    con.drawImage(this, 0,0+(off/2),imgScaledWidth,imgScaledHeight);
    }

</script>

答案 1 :(得分:0)

伸展它。如果您不想显示拉伸的图像,请不要将任何大小传递给drawImage

self.context.drawImage(this, 0, 0);