Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Simple Drawing Application Perfect

Caesar Bell
Caesar Bell
24,827 Points

Resetting the canvas with the reset button

I created a reset button, but I am trying to setup the drawing app to where a user can click on the button and reset the canvas without having to always refresh the page to have a fresh new canvas to draw on. So far my code is

<button id="resetCanvas">Reset</button>
//When clicked reset the canvas back to an empy canvas 
$("#resetCanvas").click(function(){
    context.width = context.width; 
});

I did some reseach and most doc say the code above is the simpliest way to reset the canvas. Or I could use the following code

ctx.clearRect(0, 0, canvas.width, canvas.height);

But neither one works for me can someone help me

3 Answers

simhub
simhub
26,543 Points

Hi Caesar, maybe this helps:

$("#resetCanvas").click(function(){
  var canvas= document.getElementById('canvas');
 var ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0,  canvas.width, canvas.height);
});
Caesar Bell
Caesar Bell
24,827 Points

Okay thank you, but I had something similar to that using the jquery method. But what I was missing was using the [0] which selected the first element. Here is the updated code

//When clicked reset the canvas back to an empy canvas 
$("#resetCanvas").click(function(){
        //Used the [0] to select the correct element in canvas
    context.clearRect(0,0, canvas[0].width, canvas[0].height); 
});
Niall Maher
Niall Maher
16,985 Points

I still can't get this to work :/ Your above code isn't working either! My poor head can't get around this one :P

Caesar Bell
Caesar Bell
24,827 Points

How is the rest of your code setup?

Cesar, make sure that your variables are correct. I was playing around with this, and it didn't work at first. I noticed that my variable for selecting the canvas was $canvas.

'''$("#resetCanvas").click(function(){ //Used the [0] to select the correct element in canvas context.clearRect(0,0, $canvas[0].width, $canvas[0].height); ''' });

Thanks! This totally solved the problem I was having because I was trying to clear on the canvas element width and height.