问题
When using the .toImage() method in KineticJS, I always seem to get a much larger image than is really necessary, with the piece I need taking up only the top left corner of the data image. My stage is scaled based on window size and a pre-defined initial size (on window resize, resize stage function called which sets the scale and the size of the container). Should I be setting some sort of crop when I use toImage() to compensate for this? Looking at the image, it seems that the overall image is about twice the size it needs to be, and the piece I need is about half the size I need, when the scale is at around 0.5 (the stage is about half size because I use Chrome and leave the developer bar open at the bottom for debugging).
Here's what I'm using now:
desc.toImage({
width: sideW / cvsObj.scale,
height: sideH / cvsObj.scale,
callback: function(img) {
desc.hide();
sideImg.transitionTo({x : sideW / 2, width : 0, duration : 0.25, callback : function() {
// add image to emulate content
var params = {name : 'descimg', width : sideW, height : sideH, image : img, x : sideW / 2, y : 0};
var image = new Kinetic.Image(params);
side.add(image);
image.setWidth(1);
sideImg.hide();
image.transitionTo({x : 0, width : sideW, duration : 0.25, callback : function() {
side.add(desc);
desc.show();
image.hide();
cvsObj.page.draw();
}});
}});
}
});
回答1:
There have been improvements to KineticJs over time and functions work in a 'better' way nowadays. Try the new KineticJS 4.3:
http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.0.min.js
回答2:
I posted this question two and a half months ago, and received no replies until today. I've kept up-to-date with KineticJS - even adding my own bug reports and code suggestions. However, recently I revisited this particular section of code and came up with something a bit better - the image I'm getting back is now properly cropped and can be inserted as is into my canvas layers. Here's the code:
// grp = kinetic group, iw = image width, ih = image height, rimg = returned image array for a deferred function, cvsobj.scale is a global stage scale variable (i scale the stage to fit the window)
getImage : function(grp, iw, ih, rimg) {
var dfr = $.Deferred();
var gp = grp.getAbsolutePosition();
grp.toImage({
width: iw * cvsObj.scale,
height: ih * cvsObj.scale,
x : gp.x,
y : gp.y,
callback: function(img) {
rimg.push(img);
dfr.resolve(rimg);
}
});
return dfr.promise();
}
This is an extended prototype function - part of a sub-section functionality for converting an entire layer or section of a layer into an image specifically for manipulating in an animation sequence. Hopefully this helps someone else.
来源:https://stackoverflow.com/questions/13164226/kineticjs-toimage-proper-method-for-creating-image-from-region-group