toDataURL() is now synchronous, and works with all nodes, including the stage, layers, groups, and shapes. This also sets things up nicely for node caching. You can now cache anything, including the whole stage, layers, groups, or shapes, manifested as Kinetic Images that were instantiated with data urls

This commit is contained in:
Eric Rowell 2012-07-14 18:10:37 -07:00
parent d62df7ba5c
commit 4692c51c74
11 changed files with 295 additions and 219 deletions

145
dist/kinetic-core.js vendored
View File

@ -288,9 +288,9 @@ Kinetic.Type = {
var context = canvas.getContext('2d');
context.putImageData(arg, 0, 0);
var dataUrl = canvas.toDataURL();
var imageObj = new Image();
imageObj.src = dataUrl;
return imageObj;
var imageObj = new Image();
imageObj.src = dataUrl;
return imageObj;
}
// default
@ -1284,6 +1284,31 @@ Kinetic.Node = Kinetic.Class.extend({
getImageData: function() {
return this.imageData;
},
/**
* Creates a composite data URL. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0)
* @name toDataURL
* @methodOf Kinetic.Stage.prototype
* @param {String} [mimeType]
* @param {Number} [quality]
*/
toDataURL: function(mimeType, quality) {
var bufferLayer = this.getStage().bufferLayer;
var bufferCanvas = bufferLayer.getCanvas();
var bufferContext = bufferLayer.getContext();
bufferLayer.clear();
this._draw(bufferLayer);
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return bufferLayer.getCanvas().toDataURL(mimeType, quality);
}
catch(e) {
return bufferLayer.getCanvas().toDataURL();
}
},
_setImageData: function(imageData) {
if(imageData && imageData.data) {
this.imageData = imageData;
@ -1836,7 +1861,7 @@ Kinetic.Container = Kinetic.Node.extend({
var child = children[n];
if(child.nodeType === 'Shape') {
if(child.isVisible() && stage.isVisible()) {
child._draw(layer ? layer : child.getLayer());
child._draw( layer ? layer : child.getLayer());
}
}
else {
@ -1995,48 +2020,6 @@ Kinetic.Stage = Kinetic.Container.extend({
layers[n].clear();
}
},
/**
* Creates a composite data URL and passes it to a callback. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0)
* @name toDataURL
* @methodOf Kinetic.Stage.prototype
* @param {function} callback
* @param {String} mimeType (optional)
* @param {Number} quality (optional)
*/
toDataURL: function(callback, mimeType, quality) {
var bufferLayer = this.bufferLayer;
var bufferContext = bufferLayer.getContext();
var layers = this.children;
var that = this;
function addLayer(n) {
var dataURL = layers[n].getCanvas().toDataURL();
var imageObj = new Image();
imageObj.onload = function() {
bufferContext.drawImage(this, 0, 0);
n++;
if(n < layers.length) {
addLayer(n);
}
else {
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
callback(bufferLayer.getCanvas().toDataURL(mimeType, quality));
}
catch(exception) {
callback(bufferLayer.getCanvas().toDataURL());
}
}
};
imageObj.src = dataURL;
}
bufferLayer.clear();
addLayer(0);
},
/**
* serialize stage and children as a JSON object
* @name toJSON
@ -2190,6 +2173,51 @@ Kinetic.Stage = Kinetic.Container.extend({
getDOM: function() {
return this.content;
},
/**
* Creates a composite data URL. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0). Note that this method works
* differently from toDataURL() for other nodes because it generates an absolute dataURL
* based on what's draw onto the canvases for each layer, rather than drawing
* the current state of each node
* @name toDataURL
* @methodOf Kinetic.Stage.prototype
* @param {String} [mimeType]
* @param {Number} [quality]
*/
toDataURL: function(mimeType, quality) {
var bufferLayer = this.bufferLayer;
var bufferCanvas = bufferLayer.getCanvas();
var bufferContext = bufferLayer.getContext();
var layers = this.children;
bufferLayer.clear();
for(var n = 0; n < layers.length; n++) {
var layer = layers[n];
var layerUrl;
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
layerUrl = layer.getCanvas().toDataURL(mimeType, quality);
}
catch(e) {
layerUrl = layer.getCanvas().toDataURL();
}
var imageObj = new Image();
imageObj.src = layerUrl;
bufferContext.drawImage(imageObj, 0, 0);
}
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return bufferLayer.getCanvas().toDataURL(mimeType, quality);
}
catch(e) {
return bufferLayer.getCanvas().toDataURL();
}
},
_resizeDOM: function() {
var width = this.attrs.width;
var height = this.attrs.height;
@ -3014,6 +3042,28 @@ Kinetic.Layer = Kinetic.Container.extend({
getContext: function() {
return this.context;
},
/**
* Creates a composite data URL. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0). Note that this method works
* differently from toDataURL() for other nodes because it generates an absolute dataURL
* based on what's draw on the layer, rather than drawing
* the current state of each child node
* @name toDataURL
* @methodOf Kinetic.Stage.prototype
* @param {String} [mimeType]
* @param {Number} [quality]
*/
toDataURL: function(mimeType, quality) {
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return this.getCanvas().toDataURL(mimeType, quality);
}
catch(e) {
return this.getCanvas().toDataURL();
}
},
/**
* private draw children
*/
@ -3028,7 +3078,8 @@ Kinetic.Layer = Kinetic.Container.extend({
}
if(this.attrs.clearBeforeDraw) {
this.clear();
var clearLayer = layer ? layer : this;
clearLayer.clear();
}
if(this.isVisible()) {

File diff suppressed because one or more lines are too long

View File

@ -218,7 +218,7 @@ Kinetic.Container = Kinetic.Node.extend({
var child = children[n];
if(child.nodeType === 'Shape') {
if(child.isVisible() && stage.isVisible()) {
child._draw(layer ? layer : child.getLayer());
child._draw( layer ? layer : child.getLayer());
}
}
else {

View File

@ -107,6 +107,28 @@ Kinetic.Layer = Kinetic.Container.extend({
getContext: function() {
return this.context;
},
/**
* Creates a composite data URL. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0). Note that this method works
* differently from toDataURL() for other nodes because it generates an absolute dataURL
* based on what's draw on the layer, rather than drawing
* the current state of each child node
* @name toDataURL
* @methodOf Kinetic.Stage.prototype
* @param {String} [mimeType]
* @param {Number} [quality]
*/
toDataURL: function(mimeType, quality) {
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return this.getCanvas().toDataURL(mimeType, quality);
}
catch(e) {
return this.getCanvas().toDataURL();
}
},
/**
* private draw children
*/
@ -121,7 +143,8 @@ Kinetic.Layer = Kinetic.Container.extend({
}
if(this.attrs.clearBeforeDraw) {
this.clear();
var clearLayer = layer ? layer : this;
clearLayer.clear();
}
if(this.isVisible()) {

View File

@ -828,6 +828,31 @@ Kinetic.Node = Kinetic.Class.extend({
getImageData: function() {
return this.imageData;
},
/**
* Creates a composite data URL. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0)
* @name toDataURL
* @methodOf Kinetic.Stage.prototype
* @param {String} [mimeType]
* @param {Number} [quality]
*/
toDataURL: function(mimeType, quality) {
var bufferLayer = this.getStage().bufferLayer;
var bufferCanvas = bufferLayer.getCanvas();
var bufferContext = bufferLayer.getContext();
bufferLayer.clear();
this._draw(bufferLayer);
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return bufferLayer.getCanvas().toDataURL(mimeType, quality);
}
catch(e) {
return bufferLayer.getCanvas().toDataURL();
}
},
_setImageData: function(imageData) {
if(imageData && imageData.data) {
this.imageData = imageData;

View File

@ -120,48 +120,6 @@ Kinetic.Stage = Kinetic.Container.extend({
layers[n].clear();
}
},
/**
* Creates a composite data URL and passes it to a callback. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0)
* @name toDataURL
* @methodOf Kinetic.Stage.prototype
* @param {function} callback
* @param {String} mimeType (optional)
* @param {Number} quality (optional)
*/
toDataURL: function(callback, mimeType, quality) {
var bufferLayer = this.bufferLayer;
var bufferContext = bufferLayer.getContext();
var layers = this.children;
var that = this;
function addLayer(n) {
var dataURL = layers[n].getCanvas().toDataURL();
var imageObj = new Image();
imageObj.onload = function() {
bufferContext.drawImage(this, 0, 0);
n++;
if(n < layers.length) {
addLayer(n);
}
else {
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
callback(bufferLayer.getCanvas().toDataURL(mimeType, quality));
}
catch(exception) {
callback(bufferLayer.getCanvas().toDataURL());
}
}
};
imageObj.src = dataURL;
}
bufferLayer.clear();
addLayer(0);
},
/**
* serialize stage and children as a JSON object
* @name toJSON
@ -315,6 +273,51 @@ Kinetic.Stage = Kinetic.Container.extend({
getDOM: function() {
return this.content;
},
/**
* Creates a composite data URL. If MIME type is not
* specified, then "image/png" will result. For "image/jpeg", specify a quality
* level as quality (range 0.0 - 1.0). Note that this method works
* differently from toDataURL() for other nodes because it generates an absolute dataURL
* based on what's draw onto the canvases for each layer, rather than drawing
* the current state of each node
* @name toDataURL
* @methodOf Kinetic.Stage.prototype
* @param {String} [mimeType]
* @param {Number} [quality]
*/
toDataURL: function(mimeType, quality) {
var bufferLayer = this.bufferLayer;
var bufferCanvas = bufferLayer.getCanvas();
var bufferContext = bufferLayer.getContext();
var layers = this.children;
bufferLayer.clear();
for(var n = 0; n < layers.length; n++) {
var layer = layers[n];
var layerUrl;
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
layerUrl = layer.getCanvas().toDataURL(mimeType, quality);
}
catch(e) {
layerUrl = layer.getCanvas().toDataURL();
}
var imageObj = new Image();
imageObj.src = layerUrl;
bufferContext.drawImage(imageObj, 0, 0);
}
try {
// If this call fails (due to browser bug, like in Firefox 3.6),
// then revert to previous no-parameter image/png behavior
return bufferLayer.getCanvas().toDataURL(mimeType, quality);
}
catch(e) {
return bufferLayer.getCanvas().toDataURL();
}
},
_resizeDOM: function() {
var width = this.attrs.width;
var height = this.attrs.height;

View File

@ -223,9 +223,9 @@ Kinetic.Type = {
var context = canvas.getContext('2d');
context.putImageData(arg, 0, 0);
var dataUrl = canvas.toDataURL();
var imageObj = new Image();
imageObj.src = dataUrl;
return imageObj;
var imageObj = new Image();
imageObj.src = dataUrl;
return imageObj;
}
// default

File diff suppressed because one or more lines are too long

View File

@ -38,43 +38,40 @@ Test.prototype.tests = {
circle.on('dragend', function() {
dragEnd = true;
});
stage.toDataURL(function(startDataUrl) {
warn(urls[0] === startDataUrl, 'start data url is incorrect');
/*
* simulate drag and drop
*/
stage._mousedown({
clientX: 380,
clientY: 98
});
test(!dragStart, 'dragstart event should not have been triggered');
test(!dragMove, 'dragmove event should not have been triggered');
test(!dragEnd, 'dragend event should not have been triggered');
stage._mousemove({
clientX: 100,
clientY: 98
});
test(dragStart, 'dragstart event was not triggered');
test(dragMove, 'dragmove event was not triggered');
test(!dragEnd, 'dragend event should not have been triggered');
stage._mouseup({
clientX: 100,
clientY: 98
});
test(dragStart, 'dragstart event was not triggered');
test(dragMove, 'dragmove event was not triggered');
test(dragEnd, 'dragend event was not triggered');
stage.toDataURL(function(endDataUrl) {
warn(urls[1] === endDataUrl, 'end data url is incorrect');
});
startDataUrl = stage.toDataURL();
warn(urls[0] === startDataUrl, 'start data url is incorrect');
/*
* simulate drag and drop
*/
stage._mousedown({
clientX: 380,
clientY: 98
});
test(!dragStart, 'dragstart event should not have been triggered');
test(!dragMove, 'dragmove event should not have been triggered');
test(!dragEnd, 'dragend event should not have been triggered');
stage._mousemove({
clientX: 100,
clientY: 98
});
test(dragStart, 'dragstart event was not triggered');
test(dragMove, 'dragmove event was not triggered');
test(!dragEnd, 'dragend event should not have been triggered');
stage._mouseup({
clientX: 100,
clientY: 98
});
test(dragStart, 'dragstart event was not triggered');
test(dragMove, 'dragmove event was not triggered');
test(dragEnd, 'dragend event was not triggered');
var endDataUrl = stage.toDataURL();
warn(urls[1] === endDataUrl, 'end data url is incorrect');
},
'DRAG AND DROP - cancel drag and drop by setting draggable to false': function(containerId) {
var stage = new Kinetic.Stage({
@ -179,31 +176,30 @@ Test.prototype.tests = {
stage.add(layer);
stage.toDataURL(function(startDataUrl) {
warn(urls[0] === startDataUrl, 'start data url is incorrect');
var startDataUrl = stage.toDataURL();
warn(urls[0] === startDataUrl, 'start data url is incorrect');
/*
* simulate drag and drop
*/
stage._mousedown({
clientX: 399,
clientY: 96
});
stage._mousemove({
clientX: 210,
clientY: 109
});
stage._mouseup({
clientX: 210,
clientY: 109
});
stage.toDataURL(function(endDataUrl) {
warn(urls[1] === endDataUrl, 'end data url is incorrect');
});
/*
* simulate drag and drop
*/
stage._mousedown({
clientX: 399,
clientY: 96
});
stage._mousemove({
clientX: 210,
clientY: 109
});
stage._mouseup({
clientX: 210,
clientY: 109
});
var endDataUrl = stage.toDataURL()
warn(urls[1] === endDataUrl, 'end data url is incorrect');
},
'EVENTS - modify fill stroke and stroke width on hover with circle': function(containerId) {
var urls = dataUrls['EVENTS - modify fill stroke and stroke width on hover with circle'];
@ -239,18 +235,16 @@ Test.prototype.tests = {
layer.add(circle);
stage.add(layer);
stage.toDataURL(function(startDataUrl) {
warn(startDataUrl === urls[0], 'start data url is incorrect');
var startDataUrl = stage.toDataURL();
warn(startDataUrl === urls[0], 'start data url is incorrect');
stage._mousemove({
clientX: 377,
clientY: 101
});
stage.toDataURL(function(endDataUrl) {
warn(urls[1] === endDataUrl, 'end data url is incorrect');
});
stage._mousemove({
clientX: 377,
clientY: 101
});
var endDataUrl = stage.toDataURL();
warn(urls[1] === endDataUrl, 'end data url is incorrect');
},
'EVENTS - path detection mousedown mouseup mouseover mouseout mousemove click dblclick / touchstart touchend touchmove tap dbltap': function(containerId) {
var stage = new Kinetic.Stage({

View File

@ -1468,14 +1468,7 @@ Test.prototype.tests = {
});
Ellipse.on('click', function() {
stage.toDataURL(function(dataUrl) {
/*
* here you can do anything you like with the data url.
* In this tutorial we'll just open the url with the browser
* so that you can see the result as an image
*/
window.open(dataUrl);
});
window.open(stage.toDataURL());
});
layer.add(Ellipse);
@ -1499,14 +1492,7 @@ Test.prototype.tests = {
});
Ellipse.on('click', function() {
stage.toDataURL(function(dataUrl) {
/*
* here you can do anything you like with the data url.
* In this tutorial we'll just open the url with the browser
* so that you can see the result as an image
*/
window.open(dataUrl);
}, 'image/jpeg', 0);
window.open(stage.toDataURL('image/jpeg', 0));
});
layer.add(Ellipse);
@ -1530,14 +1516,7 @@ Test.prototype.tests = {
});
Ellipse.on('click', function() {
stage.toDataURL(function(dataUrl) {
/*
* here you can do anything you like with the data url.
* In this tutorial we'll just open the url with the browser
* so that you can see the result as an image
*/
window.open(dataUrl);
}, 'image/jpeg', 1);
window.open(stage.toDataURL('image/jpeg', 1));
});
layer.add(Ellipse);

View File

@ -358,31 +358,28 @@ Test.prototype.tests = {
id: 'myTriangle'
});
stage.add(layer);
layer.add(group);
group.add(triangle);
layer.add(group);
stage.add(layer);
var startDataUrl = stage.toDataURL();
warn(startDataUrl === urls[0], 'start data url is incorrect');
test(triangle.getId() === 'myTriangle', 'triangle id should be myTriangle');
//console.log(stage.toJSON())
var expectedJson = '{"attrs":{"width":578,"height":200,"throttle":80,"visible":true,"listening":true,"alpha":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"dragConstraint":"none","dragBounds":{},"draggable":false},"nodeType":"Stage","children":[{"attrs":{"throttle":80,"clearBeforeDraw":true,"visible":true,"listening":true,"alpha":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"dragConstraint":"none","dragBounds":{},"draggable":false},"nodeType":"Layer","children":[{"attrs":{"visible":true,"listening":true,"alpha":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"dragConstraint":"none","dragBounds":{},"draggable":false},"nodeType":"Group","children":[{"attrs":{"detectionType":"path","visible":true,"listening":true,"alpha":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"dragConstraint":"none","dragBounds":{},"draggable":false,"fill":"#00D2FF","stroke":"black","strokeWidth":4,"id":"myTriangle"},"nodeType":"Shape"}]}]}]}';
test(stage.toJSON() === expectedJson, "problem serializing stage with custom shape");
/*
* test redrawing layer after serialization
* drawing should be the same
*/
layer.draw();
stage.toDataURL(function(startDataUrl) {
warn(startDataUrl === urls[0], 'start data url is incorrect');
var endDataUrl = stage.toDataURL();
warn(endDataUrl === urls[0], 'end data url is incorrect');
test(triangle.getId() === 'myTriangle', 'triangle id should be myTriangle');
//console.log(stage.toJSON())
var expectedJson = '{"attrs":{"width":578,"height":200,"throttle":80,"visible":true,"listening":true,"alpha":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"dragConstraint":"none","dragBounds":{},"draggable":false},"nodeType":"Stage","children":[{"attrs":{"throttle":80,"clearBeforeDraw":true,"visible":true,"listening":true,"alpha":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"dragConstraint":"none","dragBounds":{},"draggable":false},"nodeType":"Layer","children":[{"attrs":{"visible":true,"listening":true,"alpha":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"dragConstraint":"none","dragBounds":{},"draggable":false},"nodeType":"Group","children":[{"attrs":{"detectionType":"path","visible":true,"listening":true,"alpha":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"dragConstraint":"none","dragBounds":{},"draggable":false,"fill":"#00D2FF","stroke":"black","strokeWidth":4,"id":"myTriangle"},"nodeType":"Shape"}]}]}]}';
test(stage.toJSON() === expectedJson, "problem serializing stage with custom shape");
/*
* test redrawing layer after serialization
* drawing should be the same
*/
layer.draw();
stage.toDataURL(function(endDataUrl) {
warn(endDataUrl === urls[0], 'end data url is incorrect');
});
});
},
'STAGE - load stage with custom shape using json': function(containerId) {
var stage = new Kinetic.Stage({
@ -1011,7 +1008,7 @@ Test.prototype.tests = {
layer.draw();
},
'LAYER - set clearBeforeDraw to false': function(containerId) {
'LAYER - set clearBeforeDraw to false, and test toDataURL for stage, layer, group, and shape': function(containerId) {
var urls = dataUrls['LAYER - set clearBeforeDraw to false'];
var stage = new Kinetic.Stage({
@ -1025,6 +1022,8 @@ Test.prototype.tests = {
throttle: 999
});
var group = new Kinetic.Group();
var circle = new Kinetic.Ellipse({
x: 100,
y: stage.getHeight() / 2,
@ -1034,7 +1033,8 @@ Test.prototype.tests = {
strokeWidth: 4
});
layer.add(circle);
group.add(circle);
layer.add(group);
stage.add(layer);
for(var n = 0; n < 20; n++) {
@ -1042,9 +1042,10 @@ Test.prototype.tests = {
layer.draw();
}
stage.toDataURL(function(dataUrl) {
warn(urls[0] === dataUrl, 'data url is incorrect');
});
warn(urls[0] === stage.toDataURL(), 'stage data url is incorrect');
warn(urls[0] === layer.toDataURL(), 'layer data url is incorrect');
warn(urls[1] === group.toDataURL(), 'group data url is incorrect');
warn(urls[1] === circle.toDataURL(), 'shape data url is incorrect');
},
'LAYER - throttling': function(containerId) {
var stage = new Kinetic.Stage({
@ -2021,16 +2022,16 @@ Test.prototype.tests = {
stage.add(layer);
group.saveImageData();
var image = new Kinetic.Image({
image: group.getImageData(),
x: 200,
y: 0,
draggable: true
});
layer.add(image);
layer.draw();
layer.draw();
},
'SHAPE - set image fill to color then image': function(containerId) {
var imageObj = new Image();