Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 282
  • Last Modified:

How to script Canvas?

scripting help needed for this specific URL: http://jsfiddle.net/ezanker/4hfkb/6/

Simply, I am trying to script a clearCanvas drawing feature via a clearRect function. Can anyone let me know how to do this?

What I think are the snippets needed to script this are as follows, but I do not know how the JavaScript area gets resolved within the web page in order to clear Canvas1:

<a href="#canvas1">clearCanvas</a>

function clearCanvas() {            
            context.clearRect(0, 0, canvas.width, canvas.height);

Any scripting solution that properly "runs" on the JSFIDDLE site - and clears the drawing on the Canvas area - would be greatly appreciated. Thank you!
1 Solution
Robert SchuttSoftware EngineerCommented:
On the Sketch website there is an example using an eraser tool ( http://intridea.github.io/sketch.js/#tools_demo ) but unfortunately that's probably not what you want.
<a href="#tools_sketch" data-tool="eraser">Eraser</a>

Open in new window

Using that you need to click on the canvas to erase it and seems a strange way for a user to work. So I decided to go and try to find you a direct solution.

I'm not sure if any part of the code you posted is 'mandatory' but I've tried using it as you provided and built around that. It could be done more efficiently code-wise but a user will not see any difference.

step 1: set an id on the link:
<a id="clearCanvas1" href="#canvas1">clearCanvas</a>

Open in new window

step 2: add this code below the existing javascript:
    $('#clearCanvas1').on('click', function(){
        var cnv = $('#canvas1').get(0);
        var ctx = cnv.getContext('2d');
        clearCanvas(cnv, ctx); // note, this erases the canvas but not the drawing history!
        $('#canvas1').sketch().actions = []; // found it... probably not a very nice solution though

function clearCanvas(canvas, context) {            
    context.clearRect(0, 0, canvas.width, canvas.height);

Open in new window

As you can see in the comments in the code, after clearing the canvas there was a problem with the old lines returning when you start drawing again because the Sketch plugin saves a complete history of actions. After some research I found you can clear this history (line 6 in the code above) but there may be a much better way.

I saved a new version of your fiddle: http://jsfiddle.net/4hfkb/18/

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now