2012-02-12 37 views
29

我在HTML中下面的代碼:設置畫布大小的JavaScript

<canvas id="myCanvas" width =800 height=800> 

我想要的,而不是指定width800,調用JavaScript函數getWidth()到例如獲得寬

<canvas id="myCanvas" width =getWidth() height=800> 

什麼是正確的語法來做到這一點?因爲我在做什麼不行。

+0

也許這幫助: http://stackoverflow.com/questions/331052/how-to-resize-html-canvas-element – Alex 2012-02-12 18:40:06

+0

你可以涉及到這個職位一個「適合屏幕」 http://stackoverflow.com/questions/1664785/html5-canvas-resize-to-fit-window – 2012-02-12 18:42:22

+0

您的意思是''和''。這是代碼中的錯字還是錯誤? – 2012-02-12 20:20:50

回答

21
function setWidth(width) { 
    var canvas = document.getElementById("myCanvas"); 
    canvas.width = width; 
} 
+0

我想設置畫布的寬度而不僅僅是獲得寬度 – 2012-02-12 18:43:04

+0

查看更新的答案 – bozdoz 2012-02-12 18:56:58

+1

@KyriacosKafas您應該選擇一個接受的答案。 :) – bozdoz 2014-03-18 19:14:49

40

您可以設置寬度是這樣的:

function draw() { 
    var ctx = (a canvas context); 
    ctx.canvas.width = window.innerWidth; 
    ctx.canvas.height = window.innerHeight; 
    //...drawing code... 
} 
+3

繪製函數不是此代碼的最佳位置。使用onresize沒有問題。 – 2016-02-18 14:22:03

+0

亞這工作對我 – user889030 2017-04-12 09:47:25

-3

您也可以使用這個腳本,只是改變高度和寬度

<canvas id="Canvas01" width="500" height="400" style="border:2px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas> 

    <script> 
     var canvas = document.getElementById("Canvas01"); 
     var ctx = canvas.getContext("2d"); 
+2

什麼...?什麼...?什麼...? – 2016-04-17 15:26:42

0

試試這個:

var w = window, 
d = document, 
e = d.documentElement, 
g = d.getElementsByTagName('body')[0], 
xS = w.innerWidth || e.clientWidth || g.clientWidth, 
yS = w.innerHeight|| e.clientHeight|| g.clientHeight; 
alert(xS + ' × ' + yS); 

document.write('')

適用於iframe和。

+0

document.write('') – 2015-07-30 15:48:37

4

試試這個:

var setCanvasSize = function() { 
canvas.width = window.innerWidth; 
canvas.height = window.innerHeight; 
}