2017-02-14 60 views
0

以前,我跑這個JavaScript來我的畫布元素的寬度調整到窗口高度:動態設置畫布寬度完全相等的高度,而不縮放distoration

let board = document.getElementById("board"); 
function resize() { 
    // Our canvas must cover full height of screen 
    // regardless of the resolution 
    var height = window.innerHeight; 

    // So we need to calculate the proper scaled width 
    // that should work well with every resolution 
    var ratio = board.width/board.height; 
    var width = height * ratio; 

    board.style.width = width+'px'; 
    board.style.height = height+'px'; 

    window.display.w = width; 
    window.display.h = height; 
} 

window.addEventListener('load', resize, false); 
window.addEventListener('resize', resize, false); 

從那時起我的設計要求已經要求在這一個的任何一側額外的帆布。因此,我添加了

<center> 
<div class="container"> 
<canvas id="info" class="panel"></canvas> 
<canvas id="board" class="panel"></canvas> 
<canvas id="actions" class="panel"></canvas> 
</div> 

現在我的畫布在高度拉伸時畫出扭曲。我試圖在畫布代碼中以編程方式繪製5行,並且只顯示3行。

enter image description here

.container { 
    display:flex; 
    height:100vh; 
    align-items:flex-start; 
    flex-grow: 0; 
} 

.panel { 
    display:flex; 
} 

#board { 
    width:50%; 
    height:100vh; 
    background:#9b59b6; 
} 

#info { 
    width:25%; 
    height:100%; 
    background:#3498db; 
} 

#actions { 
    width:25%; 
    height:100%; 
    background:#1abc9c; 
} 

如何使用Flexbox的一個寬度分配給我的board canvas元素,使得它不會延長圖紙?

以前我拉過這種規模的:

enter image description here

我自己也嘗試設置板的寬度100vh,結果不看太大的不同。

回答

2

裏面的resize()回調函數,也請務必設置畫布的大小。目前只設置元素大小。這可能需要對董事會如何設計進行一些重組,但消除了您現在看到的問題。

function resize() { 
    // Our canvas must cover full height of screen 
    // regardless of the resolution 
    var height = window.innerHeight; 

    // So we need to calculate the proper scaled width 
    // that should work well with every resolution 
    var ratio = board.width/board.height; 
    var width = height * ratio; 

    board.width = width;  // make sure bitmap is updated as well 
    board.height = height; 

    board.style.width = width+'px'; 
    board.style.height = height+'px'; 

    window.display.w = width; 
    window.display.h = height; 
} 

可以使用或者獲得canvas元素的大小(CSS):

var rect = board.getBoundingClientRect(); 

然後設置位圖的大小相應地(注意邊框和填充其他不影響該元素的大小):

board.width = rect.width; 
board.height = rect.height; 
+0

aha! display.w和display.h是我用來繪製的。所以它看起來像我將不得不與寬度和高度一起縮放.. – quantumpotato

+0

@quantumpotato它只是意味着你需要從其他地方獲得適當的高度(例如父元素),但無論如何,主要的一點是位圖大小必須爲畫布設置。下一個問題是使用正確的尺寸... – K3N

+0

更新評論,謝謝!現在正在設置位圖的寬度和高度。現在我正在修復實際位圖繪圖的縮放 – quantumpotato

相關問題