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 trialCaesar Bell
24,829 PointsResetting 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
26,544 PointsHi 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);
});
Niall Maher
16,985 PointsI 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
24,829 PointsHow is the rest of your code setup?
allisong
10,414 PointsCesar, 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); ''' });
Nicole Chinn
8,122 PointsThanks! This totally solved the problem I was having because I was trying to clear on the canvas element width and height.
Caesar Bell
24,829 PointsCaesar Bell
24,829 PointsOkay 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