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:
The result is:
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!
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.
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%.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With