I try to get size of GWT element with CssClass using standard methods, but it returns 0;
Canvas canvas = Canvas.createIfSupported();
if(canvas == null){
/*alert code*/
}
Element e = canvas.getElement();
canvas.getElement().setClassName(canvasElement);
Context2d context = canvas.getContext2d();
int clientWidth = e.getClientWidth();
/*draw logic there*/
clientWidth is 0.
Css class:
.canvasElement{
position: absolute;
left:10px;
top:10px;
width:40px;
height:30px;
}
In which moment element size will be calculated? How can i catch catch moment?
This info can not be determined until the item is rendered. This means the item must be a) attached to the dom, and b) allowed to draw (i.e. not
display:none;). Note that you may mark it asvisibility:hidden;, as that indicates that layout may occur on it and that it may consume space, but shouldn’t actually be visible.This makes sense when you consider the css rule you want to apply to it. What happens if there is another rule, selected by
.parent .canvasElement– the browser can’t tell whether or not to apply that rule until the element is actually in the dom, so no rules are applied.Another case – a parent element scales its children, and then you add the canvas to that parent, so the width is modified by the parent. Measuring before and after attach could yield different values.
Working specifically with the code you have,
Canvasis a Widget subclass, and it implementsHasAttachHandlers, so you can add a handler for the attach event to correctly measure every time it is attached to a new context (or, just measure the first time, then remove the handler).