使用XOR在JavaScript / HTML5中绘图以删除旧的精灵 [英] Drawing in JavaScript / HTML5 using XOR to remove old sprite
问题描述
我正在为一个小游戏构建引擎,现在我刚好有一个红色的圆圈,两只小眼睛是主要角色。我有 keyPress
函数来检测运动,并且可以,但是我想使用我在QBASIC中使用很久的东西来删除字符并在新位置重画: XOR
I'm building the engine for a tiny game, and right now I have just got a red circle with two little eyes as a main character. I have keyPress
functions to detect movement, and that works, but I wanted to use something I used a long time ago in QBASIC to remove the character and redraw at a new location: XOR
基本上,在按键上会发生这种情况:
Basically, on keypress this happens:
if (code == 39) {
mainChar.drawChar();
mainChar.x += 1;
mainChar.leftEye.x += 1;
mainChar.rightEye.x += 1;
mainChar.drawChar();
}
我想在相同的空间上绘制字符,然后调整位置并绘制再次将删除第一个实例并绘制一个新实例。这是我的 drawChar
方法的一个片段:
I thought drawing the character on the same space, then adjusting the positions and drawing again would remove the first instance and draw a new one. Here is a snippet of my drawChar
method:
context.beginPath();
context.arc(mainChar.x, mainChar.y, mainChar.radius, 0, 2 * Math.PI, false);
context.closePath();
context.fillStyle = 'red';
context.fill();
context.globalCompositeOperation = "xor";
这是分类工作,而分类是指没有完全擦除第一张图。第一次调用什么都没有改变(并且字符已在加载时被调用),所以我认为XOR会完全擦除图像,因为它们的坐标和所有内容都相同?
It's 'sort-of' working, and by 'sort-of' I mean it's not completely erasing the first drawing. Nothing has shifted yet for the first call (and the character has been called on load) so I thought XOR would completely erase the image since their coordinates and everything are identical?
我是不是偏离了基础,实现了一些错误,还是有更好的方法呢?
Am I way off base, implementing something slightly wrong, or is there just a much better way to do this?
推荐答案
注意到您圈子中未删除的部分非常锯齿吗?
Have you noticed that the un-erased part of your circle is very jaggy?
这是因为画布最初使用抗锯齿来绘制您的圈子,以在视觉上平滑您的圈子的圆度。
That's because canvas originally drew your circle with anti-aliasing to visually smooth out the roundness of your circle.
对同一个圆进行XOR运算时,画布不会擦除其最初创建的抗锯齿像素。
When you XOR the same circle, canvas does not erase the anti-aliasing pixels it originally created.
斜线也会发生同样的情况。
The same will happen for slanted lines.
底线... XOR在浏览器允许之前不起作用我们关闭抗锯齿功能。
Bottom line...XOR will not work until browsers let us turn off anti-aliasing. This option has been proposed to the powers-that-be.
在此之前,您可能会更改drawChar,以便可以擦除比原来绘制的圆稍大的圆圈
Until then you might change your drawChar so that you can "erase" a slightly larger circle than you originally drew.
drawChar(50,"red");
drawChar(51,"white");
function drawChar(r,fill){
ctx.beginPath();
ctx.arc(100,100,r, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fillStyle = fill;
ctx.fill();
}
这篇关于使用XOR在JavaScript / HTML5中绘图以删除旧的精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!