2017-04-16 71 views
0

一些研究和大量的試驗和錯誤我寫了下面的條形圖之後帆布:如何在大規模的移動和桌面設備

function extractResults(container) { 
    var results = []; 
    for (result of container.children) { 
     var parts = result.innerText.split("-") 
     results.push(parseInt(parts[1].trim().split(" ")[0])); 
    } 
    return results 
} 
var results = extractResults($("#results")); 
var canvas = $("#chart"); 
var ctx = canvas.getContext("2d"); 
var margin = canvas.width * 0.005; 
var bWidth = (canvas.width - (margin * results.length))/results.length; 
var max = Math.max.apply(Math, results); 
var yScale = canvas.height/max; 
var currX = margin; 
ctx.font = "20px Arial" 
for (i = 0; i < results.length; i++) 
{ 
    var bHeight = yScale * results[i]; 
    ctx.fillStyle = "green"; 
    ctx.fillRect(currX, canvas.height - bHeight, bWidth, bHeight); 
    ctx.fillStyle = "black"; 
    ctx.fillText(i + 1, currX + bWidth/2, canvas.height - canvas.height * 0.05, bWidth/2); 
    currX += bWidth + margin; 
} 

一切都是基於畫布高度和寬度來計算,但我應該怎麼設置他們?在移動設備和桌面設備上看起來不錯的價值。我不使用任何框架和HTML看起來像這樣:

<!DOCTYPE html> 

<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1" /> 
    <title>Results - Is this site great? - easypolls</title> 

    <link rel="shortcut icon" type="image/x-icon" href="/static/favicon.ico" /> 
    <link rel="stylesheet" type="text/css" href="/static/css/style.css" /> 
    <link rel="stylesheet" type="text/css" href="/static/polls/css/polls.css" /> 
</head> 
<body> 
    <h2><a href="/">easypolls</a></h2><hr /> 

    <h3>Is this site great?</h3> 
    <p>04-14-2017 8:05 p.m. (UTC)</p> 
    <canvas id="chart"><p>Graphs are not supported by this browser.</p></canvas> 
    <ul id="results"> 

      <li>1.Yes. - 3 votes</li> 

      <li>2.No. - 0 votes</li> 

      <li>3.It looks awful! - 1 vote</li> 

    </ul> 

    <p><label>Share:<input type="text" value="http://127.0.0.1:8000/1/results/" readonly /></label></p> 
    <p><label>Embed:<input type="text" value="<iframe src=&quot;http://127.0.0.1:8000/1/results/&quot;></iframe>" readonly /></label></p> 


    <script src="/static/js/shortcuts.js"></script> 
    <script src="/static/polls/js/results.js"></script> 

</body> 
</html> 
+0

我希望這個鏈接將幫助您:http://stackoverflow.com/questions/2588181/canvas-is-stretched-when-using-css-but-normal-with-width-height-properties –

回答

1

內寬&高度

瀏覽器提供關於瀏覽器窗口大小與innerWidthinnerHeightouterWidthouterHeightscreenXscreenY信息

例如:設置畫布分辨率以匹配瀏覽器的頁面。

canvas.width = innerWidth; 
canvas.height = innerHeight; 

注意:所有像素值是CSS像素這可能不是實際的物理象素,例如當客戶端已縮放的頁面,或者如果顯示器是視網膜或非常高的清晰度顯示。由於雙線性濾波,這可能導致質量較差的畫布圖像。沒有檢測視網膜或縮放的標準方法,因此this answer提供了一個簡單的解決方案,如果這是一個問題,並且this answer提供了檢測視網膜/高分辨率顯示的更詳細的方法。

Window.screen

您還可以使用the screen對象來獲取有關該設備的屏幕信息。

相關問題