2017-06-23 104 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。