Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas size and resolution

Tags:

html

dom

css

canvas

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!

like image 915
Ovilia Avatar asked Aug 22 '12 09:08

Ovilia


People also ask

How will you set a canvas size in HTML5?

Canvas has two sizes, the size of the element and the size of the drawing surface. The default size for both element and drawing surface is 300 x 150 screen pixels. To set the height and width canvas HTML5 has two attributes: Height: With the help of Height attribute we can set the height.

How do I make my canvas fit the screen in HTML?

to set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.

Is HTML5 Canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.


1 Answers

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

like image 179
Paul Aldred-Bann Avatar answered Sep 21 '22 16:09

Paul Aldred-Bann