Clear canvas JavaScript -


i'm trying clear canvas. tried closing path, didn't change anything. also, not sure if ctxbg.close(); on right place.
thank you.

function drawgrid () {     drawgrid();     ctxbg.clearrect(0, 0, canvas.width, canvas.height);      function drawgrid () {         (var = 75; <= canvaswidth-25; i+= 25) {             ctxbg.beginpath();             ctxbg.moveto(-25 + i,55);             ctxbg.lineto(-25 + i, canvasheight - 55);             ctxbg.stroke(); }      (var = 25; <= canvasheight -75; i+= 25) {         ctxbg.beginpath();         ctxbg.moveto(55,25 + i);         ctxbg.lineto(canvaswidth-55, 25 + i);         ctxbg.stroke();           }ctxbg.close(); } 

you have 2 definitions of drawgrid() function:

function drawgrid () {  ...  function drawgrid () { 

you can have one. next, there no close() method on context, closepath(). however, not useful here. closepath not "end" path, connects first , last point in path path shape closed.

this not useful lines of course, , in case, has called before stroke().

third, (attempting to) rendering grid clear right away. won't show on canvas. need either separate operations.

here's suggested solution. 2 functions, 1 draw grid, 1 clear it:

var canvas = document.queryselector("canvas"),      canvaswidth = canvas.width, canvasheight = canvas.height,      ctxbg = canvas.getcontext("2d");    ctxbg.translate(0.5, 0.5);  // make lines sharper    function drawgrid() {      ctxbg.beginpath();   // can placed here      (var = 75; <= canvaswidth - 25; += 25) {      ctxbg.moveto(-25 + i, 55);      ctxbg.lineto(-25 + i, canvasheight - 55);    }      (var = 25; <= canvasheight - 75; += 25) {      ctxbg.moveto(55, 25 + i);      ctxbg.lineto(canvaswidth - 55, 25 + i);    }        ctxbg.stroke();      // stroke @ 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 button needs removed html button in example above, remove either using style:

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

or completely, using parentnode , removechild():

button.parentnode.removechild(button); 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -