0

I have a HTML canvas in my application. When user draws something on that canvas and performs zoom in/out, it clears the drawing from that canvas.

var wrapper = document.getElementById("signature-pad");
var canvas = wrapper.querySelector("canvas");

var signaturePad = new SignaturePad(canvas, {
  backgroundColor: 'rgb(255, 255, 255)'
});

function resizeCanvas() {   
  var ratio = Math.max(window.devicePixelRatio || 1, 1);
  canvas.width = canvas.offsetWidth * ratio;
  canvas.height = canvas.offsetHeight * ratio;
  canvas.getContext("2d").scale(ratio, ratio);
}

window.onresize = resizeCanvas;
resizeCanvas();

Is there a way present which can keep that drawing as it even when we perform zoom in-out or resize

I tried the in-memory part, but it reduces the quality of drawing

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
omkar patade
  • 1,442
  • 9
  • 34
  • 66
  • Changing the width and height of the canvas element makes the drawing disappear. Can you set the width and height using css rules instead? – James Nov 12 '18 at 13:57
  • Setting canvas.width or canvas.height will clear the buffer. You need to copy over the image data. – Lars-Kristian Johansen Nov 12 '18 at 13:58
  • There is no zoom in your code, only resize and it makes a big difference. For a zoom yoy could define the zoom 1, full quality level. For a resize, it's more conplicated... How would you want it to work exactly? Let's say your user starts with a 100 x 100 canvas, makes some drawing on it that fills all the area, the resize to 1000 x 1000. Should all the 1000 x 1000 be filled by a resized copy of the previous drawing, or should only more space be created for the current drawing area? If the former, how do you deal with aspect ratio changes? If the latter how do you deal with shrinking. – Kaiido Nov 12 '18 at 14:34
  • Do the answers to this question help? https://stackoverflow.com/questions/5517783/preventing-canvas-clear-when-resizing-window – Mixchange Jan 22 '23 at 21:08

1 Answers1

0

Reading an image from the canvas before resizing it and writing the image back after can help.

var data = signaturePad.toDataURL();    
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext("2d").scale(ratio, ratio);
signaturePad.clear();
signaturePad.fromDataURL(data); 

But it doesn't work properly when we zoom out and tries to zoom in back in signature pad

omkar patade
  • 1,442
  • 9
  • 34
  • 66