2013-06-23 38 views
2

有沒有一種方法可以創建大尺寸但低分辨率的畫布。我使用語法<canvas id="mycanvas" width="700" height="1000"></canvas>來聲明畫布。我在7英寸平板電腦上運行上面的代碼,畫布橫跨畫布的一半。有沒有辦法讓我可以創建一個畫布,再次覆蓋屏幕的一半,但分辨率較低(圖像質量較低)。 實際上,我在畫布上繪製了一些東西,然後使用canvas.toDataURL()將其另存爲圖像。我不需要獲得高質量的圖像,但我想降低生成的圖像的大小。HTML5畫布的尺寸和分辨率之間的關係

原諒我,如果這是一個愚蠢的問題

+2

HTML屬性('寬度= 「700」 HEIGHT = 「1000」')描述了畫布的*邏輯*尺寸,即,您可以在理論上將多少個像素放置在畫布上並單獨地放置。 CSS屬性('canvas#mycanvas {width:700px; height:1000px;}')描述了所述畫布的可視大小。瀏覽器將拉伸畫布的邏輯像素以適應可視區域。 – DCoder

回答

2

首先,擴大你這樣的canvas元素(在JavaScript):

canvas.width=canvas1.width*scaleFactor; 
    canvas.height=canvas1.height*scaleFactor; 

警告:如果您在使用CSS擴展畫布,你很可能會扭曲圖像畫在畫布

然後你可以使用一些額外的參數擴展您的圖像上context.drawImage

var scaleFactor=0.50; 

    ctx2.drawImage(img, 0,0,img.width,img.height, 
          0,0,img.width*scaleFactor,img.height*scaleFactor); 

enter image description here

這裏是代碼和一個小提琴:http://jsfiddle.net/m1erickson/6m8kg/

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 

<style> 
    body{ background-color: ivory; padding:15px;} 
    canvas{border:1px solid red;} 
</style> 

<script> 
$(function(){ 

    var canvas1=document.getElementById("canvas1"); 
    var ctx1=canvas1.getContext("2d"); 
    var canvas2=document.getElementById("canvas2"); 
    var ctx2=canvas2.getContext("2d"); 

    var scaleFactor=0.50; 

    var img=document.createElement("img"); 
    img.onload=function(){ 

     // draw the image full-size on the larger canvas 
     ctx1.drawImage(img,0,0); 

     // resize the canvas 
     // Don't use css to resize, it will distort your image 
     // The scaling is done with the added drawImage arguements 
     canvas2.width=canvas1.width*scaleFactor; 
     canvas2.height=canvas1.height*scaleFactor; 

     // draw a scaled-down image into the second canvas 
     ctx2.drawImage(img, 0,0,img.width,img.height, 
          0,0,img.width*scaleFactor,img.height*scaleFactor); 

    } 
    img.src="faces.png"; 


}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <p>Top canvas is full-sized</p> 
    <canvas id="canvas1" width=400 height=242></canvas><br> 
    <p>Bottom canvas is scaled down</p> 
    <canvas id="canvas2" width=300 height=300></canvas> 
</body> 
</html> 
相關問題