Jules Manson
Jules Manson

Reputation: 229

Canvas Javascript draw function not working

I am trying to separate canvas context from the actual draw functions but not working. As part of the context I wish to include the ability to resize the canvas which isn't working. The HTML works fine as this is evident with the getElementbyID working. The draw function which works fine is included for reference.

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

Upvotes: 1

Views: 3993

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32889

I see no issues with your code. It works as expected.

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>

note: do not set canvas­'s width and height using css (in first place).

Upvotes: 3

Related Questions