2017-06-23 2 views
0

Ich bin neu in Javascript also bitte mit mir nackt. Ich versuche, den Canvas-Kontext von den eigentlichen Zeichenfunktionen zu trennen, funktioniert aber nicht. Als Teil des Kontexts möchte ich die Möglichkeit mit einbeziehen, die Größe der Leinwand zu ändern, die nicht funktioniert. Der HTML-Code funktioniert einwandfrei, da dies mit dem getElementbyID funktioniert. Die Zeichenfunktion, die gut funktioniert, ist als Referenz enthalten.Leinwand Javascript Zeichenfunktion funktioniert nicht

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); 
} 

Antwort

1

Ich sehe keine Probleme mit Ihrem Code. Es funktioniert wie erwartet.

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>

Anmerkung: tun nicht Set Leinwand ‚s Breite und Höhe mit CSS (in erster Linie).