2017-06-23 11 views
0

私はJavascriptを初めて使用しています。私は実際の描画関数からキャンバスコンテキストを分離しようとしていますが、動作しません。文脈の一部として、私は働かないキャンバスのサイズを変更する機能を含めることを望みます。これは、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(最初の場所で)を使用してないセットキャンバス幅と高さ。

関連する問題