开发者

domElement.getClientWidth() and domElement.getClientHeight() return 0

开发者 https://www.devze.com 2023-04-10 13:45 出处:网络
I try to get size of GWT element with CssClass using standard methods, but it returns 0; Canvas canvas = Canvas.createIfSupported();

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 开发者_如何学JAVA= 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 as visibility: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, Canvas is a Widget subclass, and it implements HasAttachHandlers, 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).


I am not sure about how GWT work, but as i have experienced an element should be in DOM structure before we can get its clientwidth/height. As per your code, i think the canvas element has not been appended to DOM when you are trying to access its clientwidth().


Canvas width and height must be put in the HTML file , Example :

<canvas id="example" width="200" height="200">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

Html Canvas element force you to put WIDTH and HEIGHT in HTML document , doesnt let you to put it only in CSS

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号