Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can try to save the state of the canvas as a blob. For example, as image/png. There are two bad things here:

  1. A small inconvenience. Methods for converting a blob to an image and back are asynchronous. Promises have to be used.

  2. Speed. I strongly doubt that this solution is suitable for tasks that require speed - games, videos, etc.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

const saveCanvasState = (canvas) => {
  const ctx = canvas.getContext('2d');
  ctx.save(); // save state
  let blob;

  return new Promise((r) => {
    canvas.toBlob( // toBlob is async method
      (b) => {
        blob = b;

        r(() =>
          new Promise((r) => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.restore();

            const img = new Image();

            img.addEventListener('load', () => {
              URL.revokeObjectURL(img.src);
              ctx.drawImage(img, 0, 0);
              r();
            });

            img.src = URL.createObjectURL(blob);
          }));
      },
      'image/png',
      1
    );
  });
};

ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);

saveCanvasState(canvas).then((restore) => {
  ctx.fillStyle = 'black';
  ctx.fillRect(150, 40, 100, 100);
  ctx.fillRect(100, 40, 100, 100);

  restore().then(() => {
    console.log('restored, can draw');
  });
});
<canvas id="canvas"></canvas>

about 4 years ago · Juan Pablo Isaza Denunciar

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda