8

I wrote a simple example to show this.

The size of canvas is 500px * 400px. The origin size of my image is 200px * 160px with dpi of 480. I want to display this image in the canvas with the origin size so that it will not be resized, which will blur the image.

Here's the code:

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#canvas").width(500);
            $("#canvas").height(400);

            var canvas = $("#canvas").get(0);
            var ctx = canvas.getContext('2d');

            var image = new Image();
            image.src = "fish01.png"; // size is 200px * 160px

            ctx.drawImage(image, 0, 0); // same with ctx.drawImage(image, 0, 0, 200, 160); 
        });
    </script>
</head>

<body style="background-color: #ccc; margin: 0px;">
    <canvas id="canvas" style="background-color: #66c"></canvas>
</body>
</html>

Origin image is:

200px * 160px

The result is: enter image description here

I think this is strange since the size of canvas is 500px * 400px and the size of image is 200px * 160px, how would the image be out of the range of the canvas? And it seems that the image has been resized.

I want to know how to display the image with the origin size. Please give some advice. Thanks!

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
Ovilia
  • 7,066
  • 12
  • 47
  • 70

2 Answers2

13

Try adding your canvas width and height as attributes instead:

$("#canvas").attr("width", "500px");
$("#canvas").attr("height", "400px");

This defines the drawable space in the canvas, otherwise it defaults to something like 2:1 I think. I know you're using .width() and .height() but they set a unitless value, whereas we're defining it explicitly as pixles with .attr().

Example jsFiddle

Paul Aldred-Bann
  • 5,840
  • 4
  • 36
  • 55
4

When you don't add width and height attributes to canvas tag, then you render on canvas with default width and height. And

$("#canvas").width(500);
$("#canvas").height(400);

just stretch by css this tag.

So use <canvas id="canvas" width="500" height="400"></canvas>

Or use $('#canvas').attr function

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79