legalthings / angular-signature

HTML5 canvas based smooth signature drawing as angularJS directive (http://szimek.github.io/signature_pad/)
MIT License
105 stars 91 forks source link

Can't load via an Angular template #41

Closed heck4 closed 7 years ago

heck4 commented 7 years ago

I'm basically encountering this issue: http://stackoverflow.com/questions/32639020/offsetwidth-offsetheight-is-zero-when-template-loaded-by-ngroute

The offsetWidth and offsetHeight of the canvas are initially set to zero. When I look at the rendered html it has a fixed width/height on the canvas element of 0. This results in not being able to draw on the canvas because it occupies no space. I can workaround this by resizing the window, and then can draw.

However, I wrote a fix which seems to work.

I also fixed another bug that cleared the signature when you resized the window. Here is the code:

scope.onResize = function() {
    var canvas = element.find('canvas')[0];
    var ratio =  Math.max($window.devicePixelRatio || 1, 1);
    var newWidth = canvas.offsetWidth * ratio;
    var newHeight = canvas.offsetHeight * ratio;
    // The offsetWidth and offsetHeight can be zero when the canvas is initialized via before the DOM is ready.
    // Also, prevent unneccessary clearing of the image. Don't set width/height unless its actually different.
    if (newWidth > 0 && newWidth !== canvas.width) canvas.width = newWidth;
    if (newHeight > 0 && newHeight !== canvas.height) canvas.height = newHeight;
    canvas.getContext("2d").scale(ratio, ratio);
}
jasny commented 7 years ago

If you still have this issue with v1.0, please reopen this ticket and include a JSFiddle demonstration the problem.