简体   繁体   中英

Clear canvas JavaScript

I'm trying to clear the canvas. I tried closing the path, but it didn't change anything. also, I am not too sure if the ctxBg.close(); is on the right place.
Thank you.

function drawGrid () {
    drawGrid();
    ctxBg.clearRect(0, 0, canvas.width, canvas.height);

    function drawGrid () {
        for (var i = 75; i <= canvasWidth-25; i+= 25) {
            ctxBg.beginPath();
            ctxBg.moveTo(-25 + i,55);
            ctxBg.lineTo(-25 + i, canvasHeight - 55);
            ctxBg.stroke();
}

    for (var i = 25; i <= canvasHeight -75; i+= 25) {
        ctxBg.beginPath();
        ctxBg.moveTo(55,25 + i);
        ctxBg.lineTo(canvasWidth-55, 25 + i);
        ctxBg.stroke();      
    }ctxBg.close();
}

You have two definitions of the drawGrid() function:

function drawGrid () {
 ...
 function drawGrid () {

You can only have one. Next, there is no close() method on a context, only closePath() . However, this is not useful here. closePath does not "end" a path, but connects the first and last point in the path so the path shape is closed.

This is not useful with lines of course, and in any case, it has to be called before stroke().

Third, you are (attempting to) rendering the grid then clear it right away. This won't show anything on canvas. You need to either separate those operations.

Here's a suggested solution. Two functions, one to draw the grid, one to clear it:

 var canvas = document.querySelector("canvas"), canvasWidth = canvas.width, canvasHeight = canvas.height, ctxBg = canvas.getContext("2d"); ctxBg.translate(0.5, 0.5); // just to make the lines sharper function drawGrid() { ctxBg.beginPath(); // this can be placed here for (var i = 75; i <= canvasWidth - 25; i += 25) { ctxBg.moveTo(-25 + i, 55); ctxBg.lineTo(-25 + i, canvasHeight - 55); } for (var i = 25; i <= canvasHeight - 75; i += 25) { ctxBg.moveTo(55, 25 + i); ctxBg.lineTo(canvasWidth - 55, 25 + i); } ctxBg.stroke(); // stroke all at once // remove button code (ref. comments) var button = document.querySelector("button"); button.parentNode.removeChild(button); } function clearGrid() { ctxBg.clearRect(0, 0, canvas.width, canvas.height); } 
 <button onclick="drawGrid()">Grid</button> <button onclick="clearGrid()">Clear</button><br> <canvas></canvas> 

Update: if the button that needs to be removed is a HTML button as in the example above, then remove it by either using style:

// assumes the button element is stored in variable button:
button.style.display = "none";

or completely, using its parentNode and removeChild() :

button.parentNode.removeChild(button);
ctxBg.clearRect(0,0,canvas.width,canvas.height);

这将清除您的画布。

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