admin管理员组

文章数量:1333618

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?

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?

Share Improve this question asked Oct 16, 2015 at 19:39 AmayAmay 1,5215 gold badges29 silver badges57 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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

本文标签: javascriptCanvas opaquechange default background colorStack Overflow