使用 Javascript 在 HTML5 中重绘画布
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11773811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redrawing Canvas in HTML5 using Javascript
提问by Ganesh Somani
I am creating a click and clear game. Once the user clicks some brick its adjacent bricks are checked for same color and all these bricks are bricks are cleared at once.
我正在创建一个点击清除游戏。一旦用户点击某个砖块,它的相邻砖块就会被检查是否有相同的颜色,并且所有这些砖块都会被立即清除。
These are Cleared using clearRect() function.
这些是使用 clearRect() 函数清除的。
Now this leaves a white patch right between the bricks above and bricks below leaving the above bricks hanging.
现在这会在上面的砖块和下面的砖块之间留下一个白色的补丁,让上面的砖块悬空。
Now i want to bring these bricks above downward. How do i do this..? Plz help
现在我想把这些砖放在上面。我该怎么做呢..?请帮忙
回答by MarcoK
The question is quite vague, but based on the title, you'll need to clear your canvas before you can redraw. Otherwise, the drawn elements would simply stack on top of each other.
这个问题很模糊,但根据标题,您需要先清除画布,然后才能重绘。否则,绘制的元素将简单地堆叠在彼此的顶部。
To do this, call the function clearRect
on the canvas itself:
为此,请调用clearRect
画布本身上的函数:
function clear() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 500, 500);
}
Where canvas
is the ID of your canvas, and 500, 500
the dimensions. Now you'll have an empty canvas where you can redraw everything again.
canvas
画布的 ID 和500, 500
尺寸在哪里。现在您将拥有一个空画布,您可以在其中重新绘制所有内容。
I once created a simple HTML5 canvas gameas well, you might learn from the source code.
我曾经也创建了一个简单的 HTML5 画布游戏,你可以从源代码中学习。
回答by Jarrod
I think I understand what you're asking. If so then you're wanting to know how to move the blocks down when the blocks below have been removed.
我想我明白你在问什么。如果是这样,那么您想知道当下面的块被移除时如何向下移动块。
This is just a matter of increasing the x position (remember the canvas starts at 0,0) with each iteration of your game loop.
这只是在游戏循环的每次迭代中增加 x 位置(记住画布从 0,0 开始)的问题。
How far to increase? Well that would be to where the highest "solid tower" is. I.E., say you have a column of 10 tokens and you remove the 7. The 3 below need all fall to the height of the remaining 6 - so that would be board height - (6*token height)
增加到什么程度?好吧,那将是最高的“实心塔”所在的地方。IE,假设您有一列 10 个标记,然后删除了 7 个。下面的 3 个需要全部落到剩余 6 个的高度 - 这样就可以了board height - (6*token height)
*
*
*
+ <- remove
* <- 6x token height (and less the board height)
*
*
*
*
*
回答by Russell
I had success at redrawing the HTML Canvas by DOM.
我成功地通过 DOM 重新绘制了 HTML Canvas。
var c = document.getElementsByName("myCanvas")[0];
if (c != null)
{
c.remove();
}
var c = document.createElement("canvas");
c.setAttribute("name", "myCanvas");
c.setAttribute("width", 900);
c.setAttribute("height", 600);
c.setAttribute("style", "border:1px solid #d3d3d3");