最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - setAttribute width for canvas as percentage value - Stack Overflow

programmeradmin0浏览0评论

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 () 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!

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./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!

Share Improve this question asked Mar 5, 2013 at 9:52 user2135133user2135133 231 silver badge3 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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.

发布评论

评论列表(0)

  1. 暂无评论