Amay
Amay

Reputation: 1521

Canvas opaque - change default background color

I'm using canvas.getContext('2d', {alpha: false}); (wiki info) to remove canvas opacity and improve performance of animation. Unfortunately after that, canvas element gain white background. Is there an option to change the default color of canvas background/color?

I tried drawImage() to fill whole area, but (because of animation) I think it is not the best solution:

var canvas = document.querySelector('#mycanvas'),
    ctx = canvas.getContext('2d', {alpha: false});

function run() {
    ctx.clearRect(0, 0, size.width, size.height);

    ctx.drawImage(bg, 0, 0, size.width, size.height);

    draw();
    update();

    requestAnimationFrame(run);
}

I really care about performance, so it would be useful to change the color only once.

Any ideas?

Upvotes: 1

Views: 9496

Answers (1)

Karmacon
Karmacon

Reputation: 3200

No. The default background is always black.

The CanvasRenderingContext2D.clearRect() method of the Canvas 2D API sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content.

Instead of clearing the canvas, just set fillRect to fill with the color you want.

var canvas = document.querySelector('#mycanvas'),
    ctx = canvas.getContext('2d', {alpha: false});

function run() {
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(0, 0, size.width, size.height);

    draw();
    update();

    requestAnimationFrame(run);
}

Upvotes: 6

Related Questions