Centering canvas-element in Google Chrome using KineticJS

In the following code sample I am using an image that is drawn onto the HTML5-canvas element. However, when testing this in Chrome it does not immediately center the image. IE doesn't have a problem with this (using IE9). When you select one of the elements in the DOM using the developer window in Chrome, somehow it THEN suddenly centers!!! Its hard to debug since you can't see what's changing what:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 2</title>

    <script type="text/javascript" src="http://www.html5canvastutorials.com/libraries/kinetic-v3.10.2.js"></script>
    <script type="text/javascript">

        window.onload = function () {
            var stage = new Kinetic.Stage({
                container: "container",
                width: 578,
                height: 200
            });
            var layer = new Kinetic.Layer();

            var imageObj = new Image();
            imageObj.onload = function () {
                var image = new Kinetic.Image({
                    x: stage.getWidth() / 2 - 53,
                    y: stage.getHeight() / 2 - 59,
                    image: imageObj,
                    width: 106,
                    height: 118
                });

                // add the shape to the layer
                layer.add(image);

                // add the layer to the stage
                stage.add(layer);
                stage.draw();
            };
            imageObj.src = "http://www.html5canvastutorials.com/demos/assets/yoda.jpg";
        };

    </script>

</head>

<body>

    <h1>Page 3</h1>
    <div style="text-align: center">
        <div id="container"></div>
    </div>

</body>

</html>

Answers


I fixed this problem as follows. Using Chrome Canary I was able to click the DOM-canvas-elements without the elements repositioning themselves (this seemed like a bug in Chrome). The last canvas-element added was not positioned css-position "relative". Doing this made sure the selections that I drew on top of the canvas became centered and thus the whole "canvas"-element (using KineticJS). I needed to use jQuery to set the css-position-property dynamically, like so:

$("#myContainerId canvas:last").css( "position", "relative" );

Need Your Help

Android webview 4.4 css 100% does not show anything

android css webview android-4.4-kitkat

In a Android webview I load up a simple html page which has a div set to 100% width and height. I works fine in the browser however on a Galaxy Nexus 4.4.2 I can not see the content div.