wrong image height in canvas

I have a canvas like this

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

Now I am trying to show image inside the canvas of some 260px width and height. But its showing the image full screened in canvas. What I am doing wrong?

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

Its showing like this

Answers


There's no reason why your code shouldn't be working based on what you've shown in the question. Here is an example based on the code you've given with some minor changes to account for not having a self variable.

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

You are stretching it. If you don't want to show the image stretched, just don't pass any size to drawImage:

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

Need Your Help

Java Tilemaps using Cliping to increase framerate: What can go WRONG?

java performance swing graphics tile

Conducting research before starting something is a good idea so I've been looking at the articles here on Stackverflow before beginning a project.

Using shared memory with fork()

c++ fork semaphore shared-memory

I already looked at the only similar post I could find, but it wasn't what I was looking for.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.