如果我在黑色背景上绘制一个绿色圆圈,然后用黑色绘制相同的圆圈,则会留下绿色阴影/发光。该圆圈实际上并未被删除。
如何使其再次纯黑并消除辉光?
我尝试过context.shadowColor = "transparent";
这是一个片段:
context.beginPath();
context.arc(x-1, y-2, 2, 0, 2*Math.PI);
context.fillStyle = "#FF0000";
//context.strokeStyle = "#FF0000";
//context.stroke();
context.fill();
context.beginPath();
context.arc(x-1, y-2, 2, 0, 2*Math.PI);
context.fillStyle = "#000000";
//context.strokeStyle = "#000000";
//context.stroke();
context.fill();
这是完整的对象:
最佳答案
如何清除 Canvas 。
根据您提供的图像的外观,您想要编写某种游戏或某种动画。
完成游戏和动画的一般方式是每帧重新绘制整个游戏屏幕。这极大地简化了渲染引擎的设计。只需更改绘制顺序即可轻松将一件事绘制在另一件事之上。要让某些东西消失,只需不渲染它即可。
我假设您知道如何加载图像
清除屏幕
您有多种方法可以清除屏幕。
// assuming ctx is the 2d Context and width and height are the canvas width and height.
ctx.clearRect(0, 0, width, height);
或者用矩形填充屏幕。
var backgroundColour = "#000";
ctx.fillStyle = backgroundColour;
ctx.fillRect(0, 0, width, height);
或者使用背景图片
var backgroundImage = new Image();
backgroundImage.src = "backgroundImage URL";
// then wait for image to load.
// then
ctx.drawImage(backgroundImage, 0, 0, width, height);
绘制 Sprite
现在您可以绘制图形了。同样,有很多方法可以做到这一点。一种方法是保留所有对象的列表,并在屏幕清除后一次性将它们全部绘制出来。
// create or load a game sprite (image)
var gameSprite = new Image();
gameSprite.src = "gameSprite URL";
// create a list of sprites.
var mySprites = [
{x : 10, y : 10, image : gameSprite}, // sprite 1
{x : 30, y : 60, image : gameSprite}, // sprite 2
{x : 70, y : 40, image : gameSprite} // sprite 3
];
// itterate the list and draw each sprite one at a time.
function renderSprites (spriteList) {
var i,len,s;
len = spriteList.length;
for (i = 0; i < len; i++) {
s = spriteList[i];
ctx.drawImage(s.image, s.x, s.y);
}
}
全部动画化
最后一件事是您需要将其与显示硬件同步,以便它以可能的最大帧速率运行,并且不会产生诸如剪切或闪烁之类的伪影。为此,您可以使用与 setTimeout
类似的 requestAnimationFrame
,但您不提供浏览器负责处理的时间。
您需要向 requestAnimationFrame
提供一个主循环函数,以便在浏览器准备好绘制下一帧时调用。在此函数中,您首先清除屏幕,执行游戏逻辑,绘制所有 Sprite ,然后请求下一帧(尽管您可以在主循环内的任何阶段请求下一帧)。
function mainLoop(time){ // requestAnimationFrame adds the argument (time).
// This is the time in milliseconds.
// clear the screen
ctx.drawImage(backgroundImage,0,0,width,height);
// do game logic here
renderSprites(mySprites); // draw the sprites
// now request the next frame and do it all again.
requestAnimationFrame(mainLoop);
}
// start the animation by requesting the first frame.
requestAnimationFrame(mainLoop);
它将以 60fps(每秒帧数)运行,并且可以轻松处理超过 100 个 Sprite (除了最基本的设备外)
关于javascript - 消除 HTML5 Canvas 绘图中的辉光?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35384569/