1

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

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.