2017-06-23 102 views
0

我是新來的Javascript,所以請裸露在我身邊。我試圖將畫布上下文從實際的繪圖函數中分離出來,但不工作。作爲上下文的一部分,我希望包括調整不工作的畫布大小的功能。 HTML工作正常,因爲getElementbyID的工作很明顯。包含了可以正常工作的繪圖函數供參考。帆布Javascript繪圖功能不工作

window.onload = function() { 
    'use strict'; 
    var ctx = getCanvas(); 
    draw(ctx); 
} 
function getCanvas() { 
    var canvas = document.getElementById('canvas'); 
    var ctx = canvas.getContext('2d'); 
    var w = canvas.width = 200; 
    var h = canvas.height = 150; 
    return ctx; 
} 
function draw(ctx) { 
    ctx.fillStyle = 'rgb(200, 0, 0)'; 
    ctx.fillRect(10, 10, 50, 50); 
    ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'; 
    ctx.fillRect(30, 30, 50, 50); 
} 

回答

1

我看不出您的代碼有問題。它按預期工作。

window.onload = function() { 
 
    'use strict'; 
 
    var ctx = getCanvas(); 
 
    draw(ctx); 
 
}; 
 

 
function getCanvas() { 
 
    var canvas = document.getElementById('canvas'); 
 
    var ctx = canvas.getContext('2d'); 
 
    var w = canvas.width = 200; 
 
    var h = canvas.height = 150; 
 
    return ctx; 
 
} 
 

 
function draw(ctx) { 
 
    ctx.fillStyle = 'rgb(200, 0, 0)'; 
 
    ctx.fillRect(10, 10, 50, 50); 
 
    ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'; 
 
    ctx.fillRect(30, 30, 50, 50); 
 
}
canvas{border: 1px solid black}
<canvas id="canvas" width="1000" height="1000"></canvas>

注:集畫布寬度和高度(在首位)使用CSS。