KineticJS icon indicating copy to clipboard operation
KineticJS copied to clipboard

Using existing canvas

Open brannondorsey opened this issue 11 years ago • 3 comments

Is there a way to make kinetic.js use an existing canvas element instead of creating one by specifying the id of the desired container when instantiating Kinetic.Stage?

brannondorsey avatar Nov 30 '13 18:11 brannondorsey

This might be interesting for me as well. I have tried using my KineticJS project inside CocoonJS wrapper and there is a special way to scale the canvas:

canvas.style.cssText="idtkscale:SCALE_TYPE;";

But if KineticJS creates the canvas, I haven't found a way to get that to work. If there was a way to create the canvas first myself - it might at least make it easier to use that property of CocoonJS.

plrdev avatar Dec 02 '13 15:12 plrdev

I'll have to look into this. Each layer has its own canvas. after creating a layer, you could try setting the canvas with layer.getCanvas()._canvas = yourCanvas. the "_canvas" property points to a native canvas element.

ericdrowell avatar Dec 02 '13 18:12 ericdrowell

I got Kinetic running on a single canvas like this:

Kinetic.SceneCanvas.prototype.init = function(config) {
    var conf = config || {};

    this.pixelRatio = 1;
    this._canvas = config.useRealCanvas ? Kinetic.Util.useRealCanvasElement() : Kinetic.Util.createCanvasElement();

    // set inline styles
    this._canvas.style.padding = 0;
    this._canvas.style.margin = 0;
    this._canvas.style.border = 0;
    this._canvas.style.background = 'transparent';
    this._canvas.style.position = 'absolute';
    this._canvas.style.top = 0;
    this._canvas.style.left = 0;
};

var canvas = null;

Kinetic.Util.useRealCanvasElement = function() {
    if (!canvas) canvas = document.getElementById('#realcanvas');
    // on some environments canvas.style is readonly
    try {
        canvas.style = canvas.style || {};
    } catch (e) {
    }
    return canvas;
};

Kinetic.Layer.prototype.____init = function (config) {
    this.nodeType = 'Layer';
    this.canvas = new Kinetic.SceneCanvas({useRealCanvas: true});
    this.hitCanvas = new Kinetic.HitCanvas();
    // call super constructor
    Kinetic.BaseLayer.call(this, config);
}

Of course I had to make sure only one layer was created and used.

lnut101 avatar Feb 24 '15 15:02 lnut101