Skip to content
Advertisement

Clear canvas by JavaScript

I am using this jQuery plugin to make free drawing over a canvas.
I want to clear the canvas for redrawing but after I do and when I click inside canvas for redrawing the old drawing that I cleared appears again

$('#canvasFirst').sketch();
$('button').on("click", (evt) => {
  var canvas = document.getElementById('canvasFirst');
  let context = canvas.getContext('2d');
  context.clearRect(0, 0, canvas.width, canvas.height);
});
canvas { border: 1px solid; vertical-align: top }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/mobomo/sketch.js@master/lib/sketch.min.js"></script>
<p>Draw on the below canvas, then press "clear" and try to draw again.</p>

<canvas id="canvasFirst">
</canvas>
<button>clear</button>

Advertisement

Answer

This plugin stores all the drawing commands in an actions array, and at each redraw it will go through that whole list and draw the full thing again. (Which allows to avoid having holes in your stroke).
The docs are very hard to grasp, but you can set this options‘s content through the .sketch("options", value) method.

As hinted in this issue, setting it to an empty Array will thus remove all the previous commands. All you have to do then is to redraw the whole scene, now empty:

const $canvas = $('#canvasFirst');
$canvas.sketch();
$('button').on("click", (evt) => {
  $canvas.sketch("actions", []);
  $canvas.sketch("redraw");
});
canvas { border: 1px solid; vertical-align: top }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/mobomo/sketch.js@master/lib/sketch.min.js"></script>
<p>Draw on the below canvas, then press "clear" and try to draw again.</p>

<canvas id="canvasFirst">
</canvas>
<button>clear</button>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement