简体   繁体   中英

Uncaught typeError cannot call method 'remove children' of undefined and Uncaught typeError cannot read property 'children' of undefined

I am doing project in android phonegap application using kineticjs and html5 I got 3 errors don't know what is the exact problem

  1. Uncaught typeError cannot call method 'remove children' of undefined at file:///android_assest/www/index.html
  2. Uncaught typeError cannot read property 'children' of undefined at file:///android_assest/www/index.html
  3. Uncaught referenceError kinetic is not defined at file:///android_assest/www/index.html

I google it but cudn't find the answer so any help would be greatful

function clearCanvas() {
        layer.removeChildren();
        layer.draw();
        haveBackground = false;
    }


       function downloadCanvas() {
        var canvas = stage.children[0].canvas;
        var oImgPNG = Canvas2Image.saveAsPNG(canvas, true);
        document.body.appendChild(oImgPNG);
    }


<img alt="" src="res/drawable-hdpi/design15.png"  id="gabby"  onClick="addClickedImage('gabby ')"/><br />

above those snippets in which i am getting error.Thanks in advance Here is the script of my programm

<script type="text/javascript" src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.1.js"></script>
<script type="text/javascript" src="assets/www/base64.js"></script>
<script type="text/javascript" src="assets/www/canvas2image.js"></script>
<script type="text/javascript">
    debugger;
    var stage;
    var layer;
    var selected;
    var wasSelected;
    var haveBackground; // first dragged image sets stage size
    /*
    * Set up canvas stage and layer
    */
    function initCanvas(id) {
        stage = new Kinetic.Stage({
            container: id,
            width: 150,
            height: 50
        });
        layer = new Kinetic.Layer();
        stage.add(layer);
        stage.draw();
    }

    /*
    * Clear canvas, start again
    */
    function clearCanvas() {
        layer.removeChildren();
        layer.draw();
        haveBackground = false;
    }


    /*
    * Download canvas
    */
    function downloadCanvas() {
        var canvas = stage.children[0].canvas;
        var oImgPNG = Canvas2Image.saveAsPNG(canvas, true);
        document.body.appendChild(oImgPNG);
    }

    /*
    * Upload File
    */
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
       .attr('src', e.target.result)
       .width(20)
       .height(20);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }
    /*
    * Resize
    */
    function resize(group, activeAnchor) {
        var tl = group.get(".tl")[0];
        var tr = group.get(".tr")[0]; group
        var br = group.get(".br")[0];
        var bl = group.get(".bl")[0];
        var handle = group.get(".handle")[0];
        var ghost = group.get(".ghost")[0];
        var flip = group.get(".flip")[0];
        var image = group.get(".image")[0];

        switch (activeAnchor.attrs.name) {
            case "tl":
                bl.setPosition(tl.attrs.x, br.attrs.y);
                tr.setPosition(br.attrs.x, tl.attrs.y);
                break;
            case "tr":
                br.setPosition(tr.attrs.x, bl.attrs.y);
                tl.setPosition(bl.attrs.x, tr.attrs.y);
                break;
            case "bl":
                br.setPosition(tr.attrs.x, bl.attrs.y);
                tl.setPosition(bl.attrs.x, tr.attrs.y);
                break;
            case "br":
                bl.setPosition(tl.attrs.x, br.attrs.y);
                tr.setPosition(br.attrs.x, tl.attrs.y);
                break;
        }

        handle.setPosition((tr.attrs.x + tl.attrs.x) / 2, tl.attrs.y - 20);
        ghost.setPosition(handle.getPosition());
        flip.setPosition((tr.attrs.x + tl.attrs.x) / 2, bl.attrs.y + 20);

        image.setPosition(tl.attrs.x, tl.attrs.y);
        image.attrs.width = tr.attrs.x - tl.attrs.x;
        image.attrs.height = bl.attrs.y - tl.attrs.y;
    }


    /*
    * Rotate
    */
    function rotate(group) {
        var c = group.getAbsolutePosition();
        var p0 = { x: c.x, y: c.y - 50 };
        var p1 = stage.getUserPosition();

        var p0c = Math.sqrt(Math.pow(c.x - p0.x, 2) + Math.pow(c.y - p0.y, 2)); // p0->c (b)   
        var p1c = Math.sqrt(Math.pow(c.x - p1.x, 2) + Math.pow(c.y - p1.y, 2)); // p1->c (a)
        var p0p1 = Math.sqrt(Math.pow(p1.x - p0.x, 2) + Math.pow(p1.y - p0.y, 2)); // p0->p1 (c)

        var deg = Math.acos((p1c * p1c + p0c * p0c - p0p1 * p0p1) / (2 * p1c * p0c));

        // fix for negative rotation
        if (p1.x < c.x) {
            deg = (360 * (Math.PI / 180)) - deg;
        }
        group.setRotation(deg);
    }


    /*
    * Flip
    */
    function flip(group) {
        group.attrs.scale.x = group.attrs.scale.x * -1;
    }


    /*
    * Fix center offset (due to resizing from a corner)
    */
    function fixCenterOffset(group) {
        var image = group.get(".image")[0]
        var currentOffset = group.getCenterOffset();
        var currentPosition = group.getPosition();
        var newOffset = { x: image.attrs.width / 2, y: image.attrs.height / 2 };
        var newPosition = {
            x: currentPosition.x - (currentOffset.x - newOffset.x),
            y: currentPosition.y - (currentOffset.y - newOffset.y)
        }

        group.setCenterOffset(newOffset);
        group.setPosition(newPosition);
        layer.draw();
    }


    /*
    * Prepare background image
    */
    function prepareBackground(img) {
        var maxWidth = 200;
        var maxHeight = 100;
        if (img.width > maxWidth) {
            img.height = (maxWidth / img.width) * img.height;
            img.width = maxWidth;
        }
        if (img.height > maxHeight) {
            img.width = (maxHeight / img.height) * img.width;
            img.height = maxHeight;
        }
        return img;
    }


    /*
    * Add an image plus anchors to the canvas using group
    */
    function initImage(img, type) {

        if (type == "background") {
            var kimggroup = initBackgroundImage(img);
        } else {
            var kimggroup = initNormalImage(img);
        }

        layer.add(kimggroup);
        stage.add(layer);

        // Draw the img
        stage.draw();
    }


    /*
    * Add background image
    */
    function initBackgroundImage(img) {

        var img = prepareBackground(img);
        stage.setSize(img.width, img.height);

        var kimggroup = new Kinetic.Group({
            x: 0,
            y: 0,
            draggable: false
        });

        // Make the img and add it to the group
        var kimg = new Kinetic.Image({
            x: 0,
            y: 0,
            image: img,
            width: img.width,
            height: img.height,
            name: "image"
        });
        kimggroup.add(kimg);

        return kimggroup;

    }


    /*
    * Add normal image
    */
    function initNormalImage(img) {

        var kimggroup = new Kinetic.Group({
            x: stage.attrs.width / 2,
            y: stage.attrs.height / 2,
            draggable: true,
            centerOffset: [img.width / 2, img.height / 2]
        });

        // Make the img and add it to the group
        var kimg = new Kinetic.Image({
            x: 0,
            y: 0,
            image: img,
            width: img.width,
            height: img.height,
            name: "image"
        });
        kimggroup.add(kimg);

        // Add anchors for resizing and rotation
        addAnchor(kimggroup, 0, 0, "tl");
        addAnchor(kimggroup, img.width, 0, "tr");
        addAnchor(kimggroup, img.width, img.height, "br");
        addAnchor(kimggroup, 0, img.height, "bl");
        addAnchor(kimggroup, img.width / 2, -20, "handle");
        addAnchor(kimggroup, img.width / 2, -20, "ghost");
        addAnchor(kimggroup, img.width / 2, img.height + 20, "flip");

        // On click make the image selected
        kimggroup.on("mousedown", function () {
            wasSelected = selected;
            selected = this;
            updateSelected();
            this.moveToTop();
            stage.draw();
        });

        kimg.on("mouseover", function () {
            document.body.style.cursor = "move";
        });

        kimg.on("mouseout", function () {
            document.body.style.cursor = "default";
        });

        // Double click to remove
        kimg.on("dblclick dbltap", function () {
            layer.remove(kimggroup);
            layer.draw();
        });

        return kimggroup;
    }


    /*
    * Create anchor and add to group
    */
    function addAnchor(group, x, y, name) {
        var config = {
            x: x,
            y: y,
            stroke: "#666",
            fill: "#ddd",
            strokeWidth: 2,
            radius: 4,
            name: name,
            draggable: true
        }
        switch (name) {
            case "handle":
                config.draggable = false;
                var anchor = addRotateAnchor(group, config);
                break;
            case "ghost":
                config.stroke = "#666";
                var anchor = addRotateGhostAnchor(group, config);
                break;
            case "flip":
                config.stroke = "#666";
                config.draggable = false;
                var anchor = addFlipAnchor(group, config);
                break;
            default:
                var anchor = addResizeAnchor(group, config);
                break;
        }
        anchor.hide();
        group.add(anchor);
    }

    /*
    * Set up resize anchor
    */
    function addResizeAnchor(group, config) {
        var anchor = new Kinetic.Circle(config);

        anchor.on("dragmove", function () {
            resize(group, this);
            layer.draw();
        });
        anchor.on("mousedown touchstart", function () {
            group.draggable(false);
            this.moveToTop();
        });
        anchor.on("dragend", function () {
            fixCenterOffset(group);
            group.draggable(true);
            layer.draw();
        });

        anchor.on("mouseover", function () {
            var layer = this.getLayer();
            document.body.style.cursor = "pointer";
            this.setStrokeWidth(3);
            layer.draw();
        });
        anchor.on("mouseout", function () {
            var layer = this.getLayer();
            document.body.style.cursor = "default";
            this.setStrokeWidth(2);
            layer.draw();
        });
        return anchor;
    }

    /*
    * Set up rotation anchor
    */
    function addRotateAnchor(group, config) {
        var anchor = new Kinetic.Circle(config);

        anchor.on("mouseover", function () {
            var layer = this.getLayer();
            document.body.style.cursor = "pointer";
            this.setStrokeWidth(3);
            layer.draw();
        });
        anchor.on("mouseout", function () {
            var layer = this.getLayer();
            document.body.style.cursor = "default";
            this.setStrokeWidth(2);
            layer.draw();
        });
        return anchor;
    }

    /*
    * Set up rotation ghost anchor
    */
    function addRotateGhostAnchor(group, config) {
        var anchor = new Kinetic.Circle(config);

        anchor.on("dragmove", function () {
            rotate(group);
            layer.draw();
        });
        anchor.on("mousedown touchstart", function () {
            group.draggable(false);
            this.moveToTop();
        });
        anchor.on("dragend", function () {
            var handle = group.get(".handle")[0];
            this.setPosition(handle.getPosition());
            group.draggable(true);
            layer.draw();
        });

        anchor.on("mouseover", function () {
            var layer = this.getLayer();
            document.body.style.cursor = "pointer";
            this.setStrokeWidth(3);
            layer.draw();
        });
        anchor.on("mouseout", function () {
            var layer = this.getLayer();
            document.body.style.cursor = "default";
            this.setStrokeWidth(2);
            layer.draw();
        });
        return anchor;
    }

    /*
    * Set up flip anchor
    */
    function addFlipAnchor(group, config) {
        var anchor = new Kinetic.Circle(config);

        anchor.on("mousedown touchstart", function () {
            flip(group);
            layer.draw();
        });

        anchor.on("mouseover", function () {
            var layer = this.getLayer();
            document.body.style.cursor = "pointer";
            this.setStrokeWidth(3);
            layer.draw();
        });
        anchor.on("mouseout", function () {
            var layer = this.getLayer();
            document.body.style.cursor = "default";
            this.setStrokeWidth(2);
            layer.draw();
        });
        return anchor;
    }


    /*
    * Show anchors only when group selected
    */
    function updateSelected() {
        // Deselect the old img if there was any
        if (wasSelected) {
            wasSelected.get(".tl")[0].hide();
            wasSelected.get(".tr")[0].hide();
            wasSelected.get(".br")[0].hide();
            wasSelected.get(".bl")[0].hide();
            wasSelected.get(".handle")[0].hide();
            wasSelected.get(".ghost")[0].hide();
            wasSelected.get(".flip")[0].hide();
        }

        // Select the new image
        selected.get(".tl")[0].show();
        selected.get(".tr")[0].show();
        selected.get(".br")[0].show();
        selected.get(".bl")[0].show();
        selected.get(".handle")[0].show();
        selected.get(".ghost")[0].show();
        selected.get(".flip")[0].show();

    }


    /*
    * Add clicked images to the canvas
    */
    function addClickedImage(name) {
        var img = document.getElementById(name);
        initImage(img, "normal");
    }


    /*
    * Listen for images dragged into canvas and add them
    */
    function setupDragAndDrop() {
        stage.content.addEventListener("dragover", function (evt) {
            evt.preventDefault();
        }, false);

        // Handle dropped image file - only Firefox and Google Chrome
        stage.content.addEventListener("drop", function (evt) {
            dragImg = new Image();
            var files = evt.dataTransfer.files;
            if (files.length > 0) {
                var file = files[0];
                if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) {
                    var reader = new FileReader();
                    reader.onload = function (evt) {
                        dragImg.src = evt.target.result;
                    };
                    reader.readAsDataURL(file);
                    dragImg.onload = function () {
                        if (!haveBackground) {
                            haveBackground = true;
                            var type = "background";
                        } else {
                            var type = "normal";
                        }
                        initImage(this, type);
                    }
                }
            }
            evt.preventDefault();
        }, false);
    }

    window.onload = function () {
        initCanvas("container");
        setupDragAndDrop();
    };

</script>

More details:

since you cannot 'remove children' of undefined, your layer is not being defined somewhere (or is removed or overwritten).

Make sure you have this somewhere:

   var layer = new Kinetic.Layer(); 

not being able to access children means the same for your stage. but simply put since 'kinetic' is not defined somewhere you are either not including the Kinetic.4.3.0.1.JS in your sources, or you are declaring it incorrectly.

Make sure you have the kinetic.js file referenced somewhere, like in either the or tags:

   <script src='http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.1.js'></script>

or link to a hard copy in your project

   <script src='../kinetic-v4.3.1.js'></script> // in this example it is located one directory up, but you could put it anywhere really.

It's scoping issue.

Your variable layer is not accessible from function clearCanvas(). Not ideal, but it works by defining the variable first, then use it later like the following;

<script>
var layer;
$( function() {
  layer = new Kinetic.Layer();
  .....
});
</script>

so does the same apply to your variable 'stage'

--- edited after your comment ---

<script>
var layer, script, stage;
function initCanvas(id) { 
  stage = new Kinetic.Stage({ container: id, width: 150, height: 50 }); 
  layer = new Kinetic.Layer(); 
  stage.add(layer); 
  stage.draw(); 
} 
</script>

if you defined 'stage = something' inside function it works like 'var stage=something'. so if you want to access stage and layer outside of function, you defined it outside of your function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM