Ovilia
Ovilia

Reputation: 7310

HTML5 Canvas size and resolution

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!

Upvotes: 8

Views: 23278

Answers (2)

Danil Speransky
Danil Speransky

Reputation: 30473

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

Upvotes: 4

Paul Aldred-Bann
Paul Aldred-Bann

Reputation: 6020

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

Upvotes: 13

Related Questions