简体   繁体   中英

Redrawing Canvas in HTML5 using Javascript

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.

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

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:

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.

I once created a simple HTML5 canvas game as well, you might learn from the source code.

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.

How far to increase? Well that would be to where the highest "solid tower" is. IE, 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)

*
*
*
+ <- remove
* <- 6x token height (and less the board height)
*  
*  
*
*
*

I had success at redrawing the HTML Canvas by DOM.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM