HTML5 canvas size and resolution

I wrote a simple example to show this.

Canvas Size 500px * 400px. The size of the original of my image is 200px * 160px with a resolution of dpi 480. I want to display this image on canvas with the size of the beginning so that it does not change, which will blur the image.

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

Original Image:

200px * 160px

Result: enter image description here

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

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

+7
source share
2 answers

Try adding canvas width and height instead as attributes:

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

This determines the allowable space in the canvas, otherwise it defaults to 2: 1, I think. I know that you use .width() and .height() , but they set the unit value, whereas we define it explicitly as pixels with .attr() .

JsFiddle example

+12
source

If you do not add the width and height attributes to the canvas tag, then you can display width and height on the canvas by default. AND

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

just stretch this tag on css.

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

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

+4
source

All Articles