1 define([ 'util/ensureCallback', 'sprites/canvas' ], function (ensureCallback, canvas) {
2 function RenderContext(sourceData, frameData) {
3 this.sourceData = sourceData;
4 this.frameData = frameData;
6 this.previousTransforms = null;
7 this.previousFrameIndex = null;
9 this.canvas = canvas();
11 this.context = this.canvas.getContext('2d');
12 this.context.globalCompositeOperation = 'source-over';
15 RenderContext.prototype.load = function load(callback) {
16 callback = ensureCallback(callback);
18 document.body.appendChild(this.canvas);
23 RenderContext.prototype.unload = function unload() {
24 if (this.canvas.parentNode) {
25 this.canvas.parentNode.removeChild(this.canvas);
29 RenderContext.prototype.clear = function clear() {
30 this.canvas.width = this.canvas.width;
31 this.previousTransforms = null;
34 RenderContext.prototype.renderFrame = function renderFrame(frameIndex) {
35 var context = this.context;
36 var sourceData = this.sourceData;
38 var transforms = this.frameData[frameIndex];
39 var count = transforms.length;
42 var previousTransforms = this.previousTransforms;
43 if (previousTransforms) {
44 // We clear with an extra 1px border to clear smoothed edges
45 var frameInfo = sourceData.getFrameInfo(this.previousFrameIndex);
46 var width = frameInfo.width + 2;
47 var height = frameInfo.height + 2;
48 for (i = 0; i < count; ++i) {
49 var m = previousTransforms[i].matrix;
50 context.setTransform(m[0], m[1], m[3], m[4], m[2], m[5]);
51 context.clearRect(-1, -1, width, height);
55 for (i = 0; i < count; ++i) {
56 var m = transforms[i].matrix;
57 context.setTransform(m[0], m[1], m[3], m[4], m[2], m[5]);
58 sourceData.drawToCanvas(context, 0, 0, frameIndex);
61 this.previousTransforms = transforms;
62 this.previousFrameIndex = frameIndex;
65 return function (element, frameData) {
66 return new RenderContext(element, frameData);