gpt4 book ai didi

javascript - Canvas 不透明 - 更改默认背景颜色

转载 作者:行者123 更新时间:2023-11-29 17:30:39 26 4
gpt4 key购买 nike

我正在使用 canvas.getContext('2d', {alpha: false}); ( wiki info ) 来移除 Canvas 不透明度并提高动画性能。不幸的是,在那之后, Canvas 元素获得了白色背景。是否有更改 Canvas 背景/颜色的默认颜色的选项?

我试过 drawImage() 来填充整个区域,但是(因为动画)我认为这不是最好的解决方案:

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

我真的很关心性能,所以只更改一次颜色会很有用。

有什么想法吗?

最佳答案

没有。默认背景始终为黑色。

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.

无需清除 Canvas ,只需设置 fillRect 以填充您想要的颜色即可。

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

关于javascript - Canvas 不透明 - 更改默认背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33178376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com