AnchovyLegend
AnchovyLegend

Reputation: 12538

Unable to clear canvas

I am having a really difficult time resetting / clearning the contents of my canvas. I am currently using the : Sketch.js plugin to generate a free form canvas. It does exactly what I need it to, however, it does not seem to have an simple canvas 'reset' function call to clear the contents.

jsfiddle: http://jsfiddle.net/k7fmq/

NOTE: I read that the 'width' method does not work in chrome, and both methods don't seem to work on a 'free-form' canvas, but only on shapes, which I did not test.

This is what I tried so far:

Markup

<div class="signature-field">
            Signature:
    <span class="sketch-container">
            <canvas style="border:1px solid grey; border-radius:7px;" id="simple_sketch" width="400" height="150"></canvas>
            <span class="save-signature">Save Signature</span>
            <span class="reset-canvas">Reset Canvas</span>
    </span>
    Date: <input type="text"><br/><br/>Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text">
</div>

JQuery (My latest attempt)

$('.reset-canvas').click(function() {
        var myCanvas = document.getElementById("#simple_sketch");
        var width = myCanvas.width;
        myCanvas.width = width + 1;

 });

Method 2:

  $('.reset-canvas').click(function() {
           canvas.width = canvas.width; 
   });

Method 3:

$('.reset-canvas').click(function() {
       var myCanvas = document.getElementById("simple_sketch");
       var ctx = myCanvas.getContext('2d');
       ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
 });

Upvotes: 0

Views: 6436

Answers (2)

Shmiddty
Shmiddty

Reputation: 13967

Try this: http://jsfiddle.net/k7fmq/1/

The sketchpad plugin keeps an array of "actions", and redraws them each update (which seems unnecessary, really, but whatevs).

var sktch = $('#simple_sketch').sketch();  // store a reference to the element.
var cleanCanvas = $('#simple_sketch')[0];

$('.save-signature').click(function(){
    /* replace canvas with image */
    var canvas = document.getElementById("simple_sketch");
    var img    = canvas.toDataURL("image/png");
    $('#simple_sketch').replaceWith('<img src="'+img+'"/>');
    $('.signature-buttons').replaceWith('');
});
$('.reset-canvas').click(function(){
    sktch.sketch().actions = [];       // this line empties the actions. 
    var myCanvas = document.getElementById("simple_sketch");
    var ctx = myCanvas.getContext('2d');

    ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
});

Upvotes: 7

Fibericon
Fibericon

Reputation: 5793

Try this:

var ctx = myCanvas.getContext('2d');
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
ctx.restore();

Upvotes: 0

Related Questions