user2135133
user2135133

Reputation: 23

setAttribute width for canvas as percentage value

i´m working on a WebApp where Users can draw on a Canvas with their Mobile Phones and Tablets. My Problem is that if i specify the size of the canvas as percentage value in CSS, the TouchDraw-Script (http://www.codeproject.com/Articles/355230/HTML-5-Canvas-A-Simple-Paint-Program-Touch-and-Mou) is not working correctly anymore. Which is sad, because otherwise it´s perfect.

So i figured that i specify width and height of the canvas directly in the Script like this:

sigCanvas.setAttribute('width', '320');
sigCanvas.setAttribute('height', '480');

Of course i have to deal with different Screen Resolutions, so a Percentage Value would be best. Is there a way to use percentage value in my code? Cause this

sigCanvas.setAttribute('width', '90%');

is not working. Thanks in advance!

Upvotes: 2

Views: 9641

Answers (1)

Daniel Imms
Daniel Imms

Reputation: 50269

Ok, so you can do what you want by attaching to the window resize event like so:

$(window).resize(callbackFunc);

Here are the changes that I made to get it working.

See on jsFiddle

$(document).ready(function () {
    initialize();

    updateSize();
});

$(window).resize(updateSize);

function updateSize() {
    var sigCanvas = document.getElementById("canvasSignature");
    var xOffset = 100;
    var yOffset = 100; // header height
    sigCanvas.setAttribute('width', window.innerWidth - xOffset);
    sigCanvas.setAttribute('height', window.innerHeight - yOffset);
}

The xOffset and yOffset can be customised to your needs, we need to subtract from the width and height of the window otherwise the canvas will go off the page. Also make sure you run it when the page loads so the size is adjusted to the correct size then.

Upvotes: 3

Related Questions