Skip to content

Commit ece5c9f

Browse files
authored
SignaturePad: fix scaling on smaller screens (#5138)
* Add resizeCanvas calculation * Revert styles in the demo * Assign styles based on canvas size * Inline two if checks * Fix naming
1 parent 385b588 commit ece5c9f

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

Source/Extensions/Blazorise.SignaturePad/wwwroot/signaturepad.js

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ export function initialize(dotNetAdapter, element, elementId, options) {
99
if (!element)
1010
return;
1111

12+
// we need to match the canvas size ans size in styles so that we can properly calculate scaling based on screen size
13+
if (element.width && element.height) {
14+
element.style.width = `${element.width}px`;
15+
element.style.height = `${element.height}px`;
16+
}
17+
1218
const sigpad = new SignaturePad(element, {
1319
minWidth: options.minLineWidth || 0.5,
1420
maxWidth: options.maxLineWidth || 2.5,
@@ -31,11 +37,14 @@ export function initialize(dotNetAdapter, element, elementId, options) {
3137
const instance = {
3238
options: options,
3339
sigpad: sigpad,
34-
dotNetAdapter: dotNetAdapter
40+
dotNetAdapter: dotNetAdapter,
41+
element: element
3542
};
3643

3744
registerToEvents(dotNetAdapter, instance);
3845

46+
resizeCanvas(sigpad, element);
47+
3948
_instances[elementId] = instance;
4049
}
4150

@@ -176,4 +185,38 @@ function getImageDataURL(sigpad, options) {
176185
}
177186

178187
return sigpad.toDataURL("image/png", options.imageQuality || 1);
188+
}
189+
190+
window.onresize = resizeAllCanvas;
191+
192+
function resizeAllCanvas() {
193+
if (_instances) {
194+
for (let i = 0; i < _instances.length; i++) {
195+
const instance = _instances[i];
196+
197+
if (instance) {
198+
resizeCanvas(instance.sigpad, instance.element);
199+
}
200+
}
201+
}
202+
}
203+
204+
function resizeCanvas(sigpad, canvas) {
205+
if (!sigpad || !canvas) {
206+
return null;
207+
}
208+
209+
// When zoomed out to less than 100%, for some very strange reason,
210+
// some browsers report devicePixelRatio as less than 1
211+
// and only part of the canvas is cleared then.
212+
const ratio = Math.max(window.devicePixelRatio || 1, 1);
213+
214+
const context = canvas.getContext("2d");
215+
216+
// This part causes the canvas to be cleared
217+
canvas.width = canvas.offsetWidth * ratio;
218+
canvas.height = canvas.offsetHeight * ratio;
219+
context.scale(ratio, ratio);
220+
221+
sigpad.fromData(sigpad.toData());
179222
}

0 commit comments

Comments
 (0)