Reputation: 15778
Testing in Chrome. If I create dynamically a canvas object, put it into a div like this:
$('<div />').css({
width: '95%',
margin: '0px auto',
border: '1px solid red'
})
.append(
$('<canvas />')
.attr({ id: 'myCanvas' })
.css({ width: '100%' })
)
.appendTo('body');
And then in all the resize events, i try to show size:
function updateCanvas() {
console.log($('#mycanvas').get(0).width);
console.log($('#mycanvas').innerWidth());
}
/* listening to whatever change it can be on the device */
var eventListen = function() {
window.addEventListener("orientationchange", eventResize, false);
window.addEventListener("resize", eventResize, false);
};
var eventResize = function() {
window.removeEventListener("orientationchange", eventResize, false);
window.removeEventListener("resize", eventResize);
window.setTimeout(function(){
/* small timeout in case of lot of resize (dragging) */
var w=innerWidth;
var h=innerHeight;
window.setTimeout(function(){
if ((innerWidth!=w) || (innerHeight!=h)) {
eventResize();
} else {
updateCanvas();
eventListen();
}
}, 100);
}, 100);
}
eventListen();
The results are differents! Pure DOM gives me actual size of the canvas, whereas $('#mycanvas').innerWidth()
gives me bigger result...
Upvotes: 0
Views: 593
Reputation: 515
I think this scheme should answer your question (found on google images)
(source: stacktrace.jp)
The difference between the width and the innerWidth is made by the padding.
EDIT: Correction
As PE pointed out, this difference is due to the fact that the width() method you are using is in fact the object property, which is different from the css property. If you don't set your canvas property the width attribute defaults to 300, and the height attribute defaults to 150. The width and height CSS properties control the size that the element displays on screen.
More info: http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting.html#attr-canvas-width
Upvotes: 2
Reputation: 42736
The difference is because you are checking two different things
get(0).width
is the canvas' object's width property, which is not affected/changed by css styling, and is set either by the element's width attribute or the .width property in js. And defaults to 300x150 as per the spec.
jQuery's width()
,innerWidth()
etc methods are calculating the layout size of the canvas element, which is affected by the css styling.
Upvotes: 1