2012-08-22 140 views
7

我寫了一個簡單的例子來展示這一點。HTML5畫布尺寸和分辨率

畫布的大小是500px * 400px。我的圖像的原始尺寸爲200px * 160px,dpi爲480.我想在原始尺寸的畫布中顯示此圖像,以免它調整大小,這會使圖像模糊。

下面的代碼:

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

原產地形象是:

200px * 160px

結果是: enter image description here

我想既然畫布的大小爲500像素,這是奇怪的* 400px和圖像的大小是200px * 160px,圖像將如何超出c的範圍anvas?而且圖像似乎已經調整大小。

我想知道如何以原點大小顯示圖像。請給點建議。謝謝!

回答

12

嘗試增加你的畫布widthheight作爲替代屬性:

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

這定義在畫布上繪製的空間,否則默認爲類似2:1,我認爲。我知道您使用的是.width().height(),但它們設置的是無單位值,而我們將其明確定義爲使用.attr()的像素。

Example jsFiddle

+0

它的工作原理,非常感謝! – Ovilia

4

當你不加widthheight屬性canvas標籤,那麼您呈現與默認widthheight畫布。和

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

只是通過CSS這個標籤伸展。

所以使用<canvas id="canvas" width="500" height="400"></canvas>

或者使用$('#canvas').attr功能

+0

但是這不會有什麼區別:'' – Ovilia