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 // Anything not simply translated is disallowed
19 var isValid = this.frameData.every(function (frame) {
20 return frame.every(function (transform) {
21 return transform.matrix[0] === 1
22 && transform.matrix[1] === 0
23 && transform.matrix[3] === 0
24 && transform.matrix[4] === 1;
29 callback(new Error("Not supported"));
33 document.body.appendChild(this.canvas);
38 RenderContext.prototype.unload = function unload() {
39 if (this.canvas.parentNode) {
40 this.canvas.parentNode.removeChild(this.canvas);
44 RenderContext.prototype.clear = function clear() {
45 this.canvas.width = this.canvas.width;
46 this.previousTransforms = null;
49 RenderContext.prototype.renderFrame = function renderFrame(frameIndex) {
50 var context = this.context;
51 var sourceData = this.sourceData;
53 var transforms = this.frameData[frameIndex];
54 var count = transforms.length;
57 var previousTransforms = this.previousTransforms;
58 if (previousTransforms) {
59 var frameInfo = sourceData.getFrameInfo(this.previousFrameIndex);
60 var width = frameInfo.width;
61 var height = frameInfo.height;
62 for (i = 0; i < count; ++i) {
63 var transform = previousTransforms[i];
64 context.setTransform(1, 0, 0, 1, Math.floor(transform.x), Math.floor(transform.y));
65 context.clearRect(0, 0, width, height);
69 for (i = 0; i < count; ++i) {
70 var transform = transforms[i];
71 context.setTransform(1, 0, 0, 1, Math.floor(transform.x), Math.floor(transform.y));
72 sourceData.drawToCanvas(context, 0, 0, frameIndex);
75 this.previousTransforms = transforms;
76 this.previousFrameIndex = frameIndex;
79 return function (element, frameData) {
80 return new RenderContext(element, frameData);