Moved drawing logic outside of tools. Previews and animations are broken. Performance is somehow degraded

This commit is contained in:
juliandescottes 2012-09-04 14:10:16 +02:00
parent 561c35c882
commit 4c4faa88e6
13 changed files with 249 additions and 263 deletions

View File

@ -127,6 +127,13 @@ ul, li {
z-index: 1; z-index: 1;
} }
.canvas-main {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.canvas-overlay { .canvas-overlay {
position: absolute; position: absolute;
top: 0; top: 0;

View File

@ -75,6 +75,9 @@
<script src="js/lib/jsColor_1_4_0/jscolor.js"></script> <script src="js/lib/jsColor_1_4_0/jscolor.js"></script>
<!-- Application libraries--> <!-- Application libraries-->
<script src="js/rendering/Frame.js"></script>
<script src="js/rendering/drawingController.js"></script>
<script src="js/rendering/FrameRenderer.js"></script>
<script src="js/FrameSheetModel.js"></script> <script src="js/FrameSheetModel.js"></script>
<script src="js/LocalStorageService.js"></script> <script src="js/LocalStorageService.js"></script>
<script src="js/Palette.js"></script> <script src="js/Palette.js"></script>

View File

@ -8,24 +8,6 @@ pskl.FrameSheetModel = (function() {
var width; var width;
var height; var height;
/**
* Create empty frame of dimension [width * height] with Constants.TRANSPARENT_COLOR
* as a default value.
*
* @private
*/
var createEmptyFrame_ = function() {
var emptyFrame = []; //new Array(width);
for (var columnIndex=0; columnIndex < width; columnIndex++) {
var columnArray = [];
for(var heightIndex = 0; heightIndex < height; heightIndex++) {
columnArray.push(Constants.TRANSPARENT_COLOR);
}
emptyFrame[columnIndex] = columnArray;
}
return emptyFrame;
};
/** /**
* @private * @private
*/ */
@ -38,33 +20,15 @@ pskl.FrameSheetModel = (function() {
return true; // I'm always right dude return true; // I'm always right dude
}, },
getAllPixels : function () {
var pixels = [];
for (var i = 0 ; i < frames.length ; i++) {
pixels = pixels.concat(this._getFramePixels(frames[i]));
}
return pixels;
},
_getFramePixels : function (frame) {
var pixels = [];
for (var i = 0 ; i < frame.length ; i++) {
var line = frame[i];
for (var j = 0 ; j < line.length ; j++) {
pixels.push(line[j]);
}
}
return pixels;
},
getUsedColors: function() { getUsedColors: function() {
var colors = {}; var colors = {};
for (var frameIndex=0; frameIndex < frames.length; frameIndex++) { for (var frameIndex=0; frameIndex < frames.length; frameIndex++) {
var currentFrame = frames[frameIndex]; var frame = frames[frameIndex];
for (var i = 0 ; i < currentFrame.length ; i++) { for (var i = 0, width = frame.getWidth(); i < width ; i++) {
var line = currentFrame[i]; var line = frame[i];
for (var j = 0 ; j < line.length ; j++) { for (var j = 0, height = frame.getHeight() ; j < height ; j++) {
colors[line[j]] = line[j]; var pixel = frame.getPixel(i, j);
colors[pixel] = pixel;
} }
} }
} }
@ -92,7 +56,7 @@ pskl.FrameSheetModel = (function() {
}, },
addEmptyFrame: function() { addEmptyFrame: function() {
frames.push(createEmptyFrame_()); frames.push(pskl.rendering.Frame.createEmpty(width, height));
}, },
getFrameCount: function() { getFrameCount: function() {
@ -101,9 +65,9 @@ pskl.FrameSheetModel = (function() {
getFrameByIndex: function(index) { getFrameByIndex: function(index) {
if (isNaN(index)) { if (isNaN(index)) {
throw "Bad argument value for getFrameByIndex method: <" + index + ">" throw "Bad argument value for getFrameByIndex method: <" + index + ">";
} else if (index < 0 || index > frames.length) { } else if (index < 0 || index > frames.length) {
throw "Out of bound index for frameSheet object." throw "Out of bound index for frameSheet object.";
} }
return frames[index]; return frames[index];
@ -116,17 +80,12 @@ pskl.FrameSheetModel = (function() {
frames.splice(index, 1); frames.splice(index, 1);
}, },
duplicateFrameByIndex: function(frameToDuplicateIndex) { duplicateFrameByIndex: function(index) {
var frame = inst.getFrameByIndex(frameToDuplicateIndex); var frame = inst.getFrameByIndex(index);
var clonedFrame = []; frames.splice(index + 1, 0, frame.clone());
for(var i=0, l=frame.length; i<l; i++) {
clonedFrame.push(frame[i].slice(0));
}
frames.splice(frameToDuplicateIndex + 1, 0, clonedFrame);
}, },
getInstance: function(width_, height_) { getInstance: function(width_, height_) {
if (isNaN(width_) || isNaN(height_)) { if (isNaN(width_) || isNaN(height_)) {
throw "Bad FrameSheetModel initialization in getInstance method."; throw "Bad FrameSheetModel initialization in getInstance method.";
} }

View File

@ -8,55 +8,11 @@
ns.BaseTool = function() {}; ns.BaseTool = function() {};
ns.BaseTool.prototype.applyToolAt = function(col, row, frame, color, canvas, dpi) {}; ns.BaseTool.prototype.applyToolAt = function(col, row, frame) {};
ns.BaseTool.prototype.moveToolAt = function(col, row, frame, color, canvas, dpi) {}; ns.BaseTool.prototype.moveToolAt = function(col, row, frame) {};
ns.BaseTool.prototype.releaseToolAt = function(col, row, frame, color, canvas, dpi) {}; ns.BaseTool.prototype.releaseToolAt = function(col, row, frame) {};
// TODO: Remove that when we have the centralized redraw loop
ns.BaseTool.prototype.drawPixelInCanvas = function (col, row, canvas, color, dpi) {
var context = canvas.getContext('2d');
if(color == undefined || color == Constants.TRANSPARENT_COLOR) {
context.clearRect(col * dpi, row * dpi, dpi, dpi);
}
else {
if(color != Constants.SELECTION_TRANSPARENT_COLOR) {
// TODO(vincz): Found a better design to update the palette, it's called too frequently.
$.publish(Events.COLOR_USED, [color]);
}
context.fillStyle = color;
context.fillRect(col * dpi, row * dpi, dpi, dpi);
}
};
// TODO: Remove that when we have the centralized redraw loop
ns.BaseTool.prototype.drawFrameInCanvas = function (frame, canvas, dpi) {
var color;
for(var col = 0, num_col = frame.length; col < num_col; col++) {
for(var row = 0, num_row = frame[col].length; row < num_row; row++) {
color = frame[col][row];
this.drawPixelInCanvas(col, row,canvas, color, dpi);
}
}
};
// For some tools, we need a fake canvas that overlay the drawing canvas. These tools are
// generally 'drap and release' based tools (stroke, selection, etc) and the fake canvas
// will help to visualize the tool interaction (without modifying the canvas).
ns.BaseTool.prototype.createCanvasOverlay = function (canvas) {
var overlayCanvas = document.createElement("canvas");
overlayCanvas.className = "canvas-overlay";
overlayCanvas.setAttribute("width", canvas.width);
overlayCanvas.setAttribute("height", canvas.height);
canvas.parentNode.appendChild(overlayCanvas);
return overlayCanvas;
};
ns.BaseTool.prototype.removeCanvasOverlays = function () {
$(".canvas-overlay").remove();
};
/** /**
* Bresenham line algorihtm: Get an array of pixels from * Bresenham line algorihtm: Get an array of pixels from

View File

@ -16,7 +16,7 @@
/** /**
* @override * @override
*/ */
ns.Eraser.prototype.applyToolAt = function(col, row, frame, color, canvas, dpi) { ns.Eraser.prototype.applyToolAt = function(col, row, frame) {
this.superclass.applyToolAt.call(this, col, row, frame, Constants.TRANSPARENT_COLOR, canvas, dpi); this.superclass.applyToolAt.call(this, col, row, frame, Constants.TRANSPARENT_COLOR);
}; };
})(); })();

View File

@ -15,16 +15,16 @@
/** /**
* @override * @override
*/ */
ns.PaintBucket.prototype.applyToolAt = function(col, row, frame, color, canvas, dpi) { ns.PaintBucket.prototype.applyToolAt = function(col, row, color, drawer) {
// Change model: // Change model:
var targetColor = frame[col][row]; var targetColor = drawer.frame.getPixel(col, row);
//this.recursiveFloodFill_(frame, col, row, targetColor, color); //this.recursiveFloodFill_(frame, col, row, targetColor, color);
this.queueLinearFloodFill_(frame, col, row, targetColor, color); this.queueLinearFloodFill_(drawer.frame, col, row, targetColor, color);
// Draw in canvas: // Draw in canvas:
// TODO: Remove that when we have the centralized redraw loop // TODO: Remove that when we have the centralized redraw loop
this.drawFrameInCanvas(frame, canvas, dpi); drawer.renderFrame();
}; };
/** /**
@ -53,37 +53,27 @@
var dx = [0, 1, 0, -1]; var dx = [0, 1, 0, -1];
try { try {
if(frame[col][row] == replacementColor) { if(frame.getPixel(col, row) == replacementColor) {
return; return;
} }
} catch(e) { } catch(e) {
// Frame out of bound exception. // Frame out of bound exception.
} }
var isInFrameBound = function(frame_, col_, row_) {
if( col_ < 0 ||
col_ >= frame_.length ||
row_ < 0 ||
row_ >= frame_[0].length) {
return false;
}
return true;
}
queue.push({"col": col, "row": row}); queue.push({"col": col, "row": row});
var loopCount = 0; var loopCount = 0;
var cellCount = frame.length * frame[0].length; var cellCount = frame.getWidth() * frame.getHeight();
while(queue.length > 0) { while(queue.length > 0) {
loopCount ++; loopCount ++;
var currentItem = queue.pop(); var currentItem = queue.pop();
frame[currentItem.col][currentItem.row] = replacementColor; frame.setPixel(currentItem.col, currentItem.row, replacementColor);
for (var i = 0; i < 4; i++) { for (var i = 0; i < 4; i++) {
var nextCol = currentItem.col + dx[i] var nextCol = currentItem.col + dx[i]
var nextRow = currentItem.row + dy[i] var nextRow = currentItem.row + dy[i]
try { try {
if (isInFrameBound(frame, nextCol, nextRow) && frame[nextCol][nextRow] == targetColor) { if (frame.isInFrame(nextCol, nextRow) && frame.getPixel(nextCol, nextRow) == targetColor) {
queue.push({"col": nextCol, "row": nextRow }); queue.push({"col": nextCol, "row": nextRow });
} }
} catch(e) { } catch(e) {

View File

@ -12,11 +12,6 @@
// Rectangle's first point coordinates (set in applyToolAt) // Rectangle's first point coordinates (set in applyToolAt)
this.startCol = null; this.startCol = null;
this.startRow = null; this.startRow = null;
// Rectangle's second point coordinates (changing dynamically in moveToolAt)
this.endCol = null;
this.endRow = null;
this.canvasOverlay = null;
}; };
pskl.utils.inherit(ns.Rectangle, ns.BaseTool); pskl.utils.inherit(ns.Rectangle, ns.BaseTool);
@ -24,26 +19,22 @@
/** /**
* @override * @override
*/ */
ns.Rectangle.prototype.applyToolAt = function(col, row, frame, color, canvas, dpi) { ns.Rectangle.prototype.applyToolAt = function(col, row, color, drawer) {
this.startCol = col; this.startCol = col;
this.startRow = row; this.startRow = row;
// The fake canvas where we will draw the preview of the rectangle:
this.canvasOverlay = this.createCanvasOverlay(canvas);
// Drawing the first point of the rectangle in the fake overlay canvas: // Drawing the first point of the rectangle in the fake overlay canvas:
this.drawPixelInCanvas(col, row, this.canvasOverlay, color, dpi); drawer.overlay.setPixel(col, row, color);
drawer.renderOverlay();
}; };
ns.Rectangle.prototype.moveToolAt = function(col, row, frame, color, canvas, dpi) { ns.Rectangle.prototype.moveToolAt = function(col, row, color, drawer) {
this.endCol = col;
this.endRow = row;
// When the user moussemove (before releasing), we dynamically compute the
// pixel to draw the line and draw this line in the overlay canvas:
var strokePoints = this.getRectanglePixels_(this.startCol, this.endCol, this.startRow, this.endRow);
// Clean overlay canvas: // Clean overlay canvas:
this.canvasOverlay.getContext("2d").clearRect( drawer.clearOverlay();
0, 0, this.canvasOverlay.width, this.canvasOverlay.height);
// When the user moussemove (before releasing), we dynamically compute the
// pixel to draw the line and draw this line in the overlay :
var strokePoints = this.getRectanglePixels_(this.startCol, col, this.startRow, row);
// Drawing current stroke: // Drawing current stroke:
for(var i = 0; i< strokePoints.length; i++) { for(var i = 0; i< strokePoints.length; i++) {
@ -51,39 +42,29 @@
if(color == Constants.TRANSPARENT_COLOR) { if(color == Constants.TRANSPARENT_COLOR) {
color = Constants.SELECTION_TRANSPARENT_COLOR; color = Constants.SELECTION_TRANSPARENT_COLOR;
} }
this.drawPixelInCanvas(strokePoints[i].col, strokePoints[i].row, this.canvasOverlay, color, dpi); drawer.overlay.setPixel(strokePoints[i].col, strokePoints[i].row, color);
} }
drawer.renderOverlay();
}; };
/** /**
* @override * @override
*/ */
ns.Rectangle.prototype.releaseToolAt = function(col, row, frame, color, canvas, dpi) { ns.Rectangle.prototype.releaseToolAt = function(col, row, color, drawer) {
this.endCol = col;
this.endRow = row;
// If the stroke tool is released outside of the canvas, we cancel the stroke: // If the stroke tool is released outside of the canvas, we cancel the stroke:
// TODO: Mutualize this check in common method if(drawer.frame.isInFrame(col, row)) {
if(col < 0 || row < 0 || col > frame.length || row > frame[0].length) { var strokePoints = this.getRectanglePixels_(this.startCol, col, this.startRow, row);
this.removeCanvasOverlays();
return;
}
// The user released the tool to draw a line. We will compute the pixel coordinate, impact
// the model and draw them in the drawing canvas (not the fake overlay anymore)
var strokePoints = this.getRectanglePixels_(this.startCol, this.endCol, this.startRow, this.endRow);
for(var i = 0; i< strokePoints.length; i++) { for(var i = 0; i< strokePoints.length; i++) {
// Change model: // Change model:
frame[strokePoints[i].col][strokePoints[i].row] = color; drawer.frame.setPixel(strokePoints[i].col, strokePoints[i].row, color);
}
// The user released the tool to draw a line. We will compute the pixel coordinate, impact
// the model and draw them in the drawing canvas (not the fake overlay anymore)
// Draw in canvas: // Draw in canvas:
// TODO: Remove that when we have the centralized redraw loop // TODO: Remove that when we have the centralized redraw loop
this.drawPixelInCanvas(strokePoints[i].col, strokePoints[i].row, canvas, color, dpi); drawer.renderFrame();
} }
drawer.clearOverlay();
// For now, we are done with the stroke tool and don't need an overlay anymore:
this.removeCanvasOverlays();
}; };
/** /**

View File

@ -7,7 +7,7 @@
var ns = $.namespace("pskl.drawingtools"); var ns = $.namespace("pskl.drawingtools");
ns.SimplePen = function() { ns.SimplePen = function() {
this.toolId = "tool-pen" this.toolId = "tool-pen";
}; };
this.previousCol = null; this.previousCol = null;
@ -18,20 +18,17 @@
/** /**
* @override * @override
*/ */
ns.SimplePen.prototype.applyToolAt = function(col, row, frame, color, canvas, dpi) { ns.SimplePen.prototype.applyToolAt = function(col, row, color, drawer) {
this.previousCol = col; this.previousCol = col;
this.previousRow = row; this.previousRow = row;
if (color != frame[col][row]) { drawer.frame.setPixel(col, row, color);
frame[col][row] = color;
}
// Draw on canvas: // Draw on canvas:
// TODO: Remove that when we have the centralized redraw loop // TODO: Remove that when we have the centralized redraw loop
this.drawPixelInCanvas(col, row, canvas, color, dpi); drawer.renderFramePixel(col, row);
}; };
ns.SimplePen.prototype.moveToolAt = function(col, row, frame, color, canvas, dpi) { ns.SimplePen.prototype.moveToolAt = function(col, row, color, drawer) {
if((Math.abs(col - this.previousCol) > 1) || (Math.abs(row - this.previousRow) > 1)) { if((Math.abs(col - this.previousCol) > 1) || (Math.abs(row - this.previousRow) > 1)) {
// The pen movement is too fast for the mousemove frequency, there is a gap between the // The pen movement is too fast for the mousemove frequency, there is a gap between the
@ -39,11 +36,11 @@
// We fill the gap by calculating missing dots (simple linear interpolation) and draw them. // We fill the gap by calculating missing dots (simple linear interpolation) and draw them.
var interpolatedPixels = this.getLinePixels_(col, this.previousCol, row, this.previousRow); var interpolatedPixels = this.getLinePixels_(col, this.previousCol, row, this.previousRow);
for(var i=0, l=interpolatedPixels.length; i<l; i++) { for(var i=0, l=interpolatedPixels.length; i<l; i++) {
this.applyToolAt(interpolatedPixels[i].col, interpolatedPixels[i].row, frame, color, canvas, dpi); this.applyToolAt(interpolatedPixels[i].col, interpolatedPixels[i].row, color, drawer);
} }
} }
else { else {
this.applyToolAt(col, row, frame, color, canvas, dpi); this.applyToolAt(col, row, color, drawer);
} }
this.previousCol = col; this.previousCol = col;

View File

@ -12,9 +12,6 @@
// Stroke's first point coordinates (set in applyToolAt) // Stroke's first point coordinates (set in applyToolAt)
this.startCol = null; this.startCol = null;
this.startRow = null; this.startRow = null;
// Stroke's second point coordinates (changing dynamically in moveToolAt)
this.endCol = null;
this.endRow = null;
this.canvasOverlay = null; this.canvasOverlay = null;
}; };
@ -24,7 +21,7 @@
/** /**
* @override * @override
*/ */
ns.Stroke.prototype.applyToolAt = function(col, row, frame, color, canvas, dpi) { ns.Stroke.prototype.applyToolAt = function(col, row, color, drawer) {
this.startCol = col; this.startCol = col;
this.startRow = row; this.startRow = row;
@ -36,17 +33,15 @@
// frame model and canvas rendering. // frame model and canvas rendering.
// The fake canvas where we will draw the preview of the stroke: // The fake canvas where we will draw the preview of the stroke:
this.canvasOverlay = this.createCanvasOverlay(canvas);
// Drawing the first point of the stroke in the fake overlay canvas: // Drawing the first point of the stroke in the fake overlay canvas:
this.drawPixelInCanvas(col, row, this.canvasOverlay, color, dpi); drawer.updateOverlay(col, row, color);
drawer.renderOverlay();
}; };
ns.Stroke.prototype.moveToolAt = function(col, row, frame, color, canvas, dpi) { ns.Stroke.prototype.moveToolAt = function(col, row, color, drawer) {
this.endCol = col;
this.endRow = row;
// When the user moussemove (before releasing), we dynamically compute the // When the user moussemove (before releasing), we dynamically compute the
// pixel to draw the line and draw this line in the overlay canvas: // pixel to draw the line and draw this line in the overlay canvas:
var strokePoints = this.getLinePixels_(this.startCol, this.endCol, this.startRow, this.endRow); var strokePoints = this.getLinePixels_(this.startCol, col, this.startRow, row);
// Clean overlay canvas: // Clean overlay canvas:
this.canvasOverlay.getContext("2d").clearRect( this.canvasOverlay.getContext("2d").clearRect(
@ -64,39 +59,29 @@
// eg deleting the equivalent of a stroke. // eg deleting the equivalent of a stroke.
color = Constants.SELECTION_TRANSPARENT_COLOR; color = Constants.SELECTION_TRANSPARENT_COLOR;
} }
this.drawPixelInCanvas(strokePoints[i].col, strokePoints[i].row, this.canvasOverlay, color, dpi); drawer.updateOverlay(strokePoints[i].col, strokePoints[i].row, color);
} }
}; };
/** /**
* @override * @override
*/ */
ns.Stroke.prototype.releaseToolAt = function(col, row, frame, color, canvas, dpi) { ns.Stroke.prototype.releaseToolAt = function(col, row, color, drawer) {
this.endCol = col;
this.endRow = row;
// If the stroke tool is released outside of the canvas, we cancel the stroke: // If the stroke tool is released outside of the canvas, we cancel the stroke:
// TODO: Mutualize this check in common method // TODO: Mutualize this check in common method
if(col < 0 || row < 0 || col > frame.length || row > frame[0].length) { if(drawer.frame.isInFrame(col, row)) {
this.removeCanvasOverlays();
return;
}
// The user released the tool to draw a line. We will compute the pixel coordinate, impact // The user released the tool to draw a line. We will compute the pixel coordinate, impact
// the model and draw them in the drawing canvas (not the fake overlay anymore) // the model and draw them in the drawing canvas (not the fake overlay anymore)
var strokePoints = this.getLinePixels_(this.startCol, this.endCol, this.startRow, this.endRow); var strokePoints = this.getLinePixels_(this.startCol, col, this.startRow, row);
for(var i = 0; i< strokePoints.length; i++) { for(var i = 0; i< strokePoints.length; i++) {
// Change model: // Change model:
frame[strokePoints[i].col][strokePoints[i].row] = color; drawer.updateFrame(strokePoints[i].col, strokePoints[i].row, color);
}
// Draw in canvas: // Draw in canvas:
// TODO: Remove that when we have the centralized redraw loop // TODO: Remove that when we have the centralized redraw loop
this.drawPixelInCanvas(strokePoints[i].col, strokePoints[i].row, canvas, color, dpi); drawer.renderFrame();
} }
// For now, we are done with the stroke tool and don't need an overlay anymore: // For now, we are done with the stroke tool and don't need an overlay anymore:
this.removeCanvasOverlays(); drawer.clearOverlay();
}; };
})(); })();

View File

@ -90,6 +90,13 @@ $.namespace("pskl");
this.initAnimationPreview(); this.initAnimationPreview();
this.startAnimation(); this.startAnimation();
var frame = frameSheet.getFrameByIndex(this.getActiveFrameIndex());
this.drawer = new pskl.rendering.DrawingController(
frame,
$('#drawing-canvas-container')[0],
drawingCanvasDpi
);
pskl.ToolSelector.init(); pskl.ToolSelector.init();
pskl.Palette.init(frameSheet); pskl.Palette.init(frameSheet);
}, },
@ -153,23 +160,13 @@ $.namespace("pskl");
initDrawingArea : function() { initDrawingArea : function() {
drawingAreaContainer = $('#drawing-canvas-container')[0]; drawingAreaContainer = $('#drawing-canvas-container')[0];
drawingAreaCanvas = document.createElement("canvas");
drawingAreaCanvas.className = 'canvas';
drawingAreaCanvas.setAttribute('width', '' + framePixelWidth * drawingCanvasDpi);
drawingAreaCanvas.setAttribute('height', '' + framePixelHeight * drawingCanvasDpi);
drawingAreaContainer.setAttribute('style',
'width:' + framePixelWidth * drawingCanvasDpi + 'px; height:' + framePixelHeight * drawingCanvasDpi + 'px;');
drawingAreaCanvas.setAttribute('oncontextmenu', 'piskel.onCanvasContextMenu(event)');
drawingAreaContainer.appendChild(drawingAreaCanvas);
var body = document.getElementsByTagName('body')[0]; var body = document.getElementsByTagName('body')[0];
body.setAttribute('onmouseup', 'piskel.onDocumentBodyMouseup(event)'); body.setAttribute('onmouseup', 'piskel.onDocumentBodyMouseup(event)');
drawingAreaContainer.style.width = framePixelWidth * drawingCanvasDpi + "px";
drawingAreaContainer.style.height = framePixelHeight * drawingCanvasDpi + "px";
drawingAreaContainer.setAttribute('oncontextmenu', 'piskel.onCanvasContextMenu(event)');
drawingAreaContainer.setAttribute('onmousedown', 'piskel.onCanvasMousedown(event)'); drawingAreaContainer.setAttribute('onmousedown', 'piskel.onCanvasMousedown(event)');
drawingAreaContainer.setAttribute('onmousemove', 'piskel.onCanvasMousemove(event)'); drawingAreaContainer.setAttribute('onmousemove', 'piskel.onCanvasMousemove(event)');
this.drawFrameToCanvas(currentFrame, drawingAreaCanvas, drawingCanvasDpi);
}, },
initPreviewSlideshow: function() { initPreviewSlideshow: function() {
@ -320,10 +317,9 @@ $.namespace("pskl");
currentToolBehavior.applyToolAt( currentToolBehavior.applyToolAt(
spriteCoordinate.col, spriteCoordinate.col,
spriteCoordinate.row, spriteCoordinate.row,
currentFrame,
penColor, penColor,
drawingAreaCanvas, this.drawer
drawingCanvasDpi); );
$.publish(Events.LOCALSTORAGE_REQUEST); $.publish(Events.LOCALSTORAGE_REQUEST);
}, },
@ -339,10 +335,9 @@ $.namespace("pskl");
currentToolBehavior.moveToolAt( currentToolBehavior.moveToolAt(
spriteCoordinate.col, spriteCoordinate.col,
spriteCoordinate.row, spriteCoordinate.row,
currentFrame,
penColor, penColor,
drawingAreaCanvas, this.drawer
drawingCanvasDpi); );
// TODO(vincz): Find a way to move that to the model instead of being at the interaction level. // TODO(vincz): Find a way to move that to the model instead of being at the interaction level.
// Eg when drawing, it may make sense to have it here. However for a non drawing tool, // Eg when drawing, it may make sense to have it here. However for a non drawing tool,
@ -372,10 +367,9 @@ $.namespace("pskl");
currentToolBehavior.releaseToolAt( currentToolBehavior.releaseToolAt(
spriteCoordinate.col, spriteCoordinate.col,
spriteCoordinate.row, spriteCoordinate.row,
currentFrame,
penColor, penColor,
drawingAreaCanvas, this.drawer
drawingCanvasDpi); );
}, },
// TODO(vincz/julz): Refactor to make this disappear in a big event-driven redraw loop // TODO(vincz/julz): Refactor to make this disappear in a big event-driven redraw loop
@ -408,7 +402,7 @@ $.namespace("pskl");
}, },
getRelativeCoordinates : function (x, y) { getRelativeCoordinates : function (x, y) {
var canvasRect = drawingAreaCanvas.getBoundingClientRect(); var canvasRect = $(".canvas-main")[0].getBoundingClientRect();
return { return {
x : x - canvasRect.left, x : x - canvasRect.left,
y : y - canvasRect.top y : y - canvasRect.top

View File

@ -0,0 +1,64 @@
(function () {
var ns = $.namespace("pskl.rendering");
ns.DrawingController = function (frame, container, dpi) {
this.dpi = dpi;
// Public
this.frame = frame;
this.overlay = ns.Frame.createEmptyFromFrame(frame);
// Private
this.container = container;
this.mainCanvas = this.createMainCanvas();
this.overlayCanvas = this.createOverlayCanvas();
this.renderer = new ns.FrameRenderer();
};
ns.DrawingController.prototype.renderFrame = function () {
this.renderer.render(this.frame, this.mainCanvas, this.dpi);
};
ns.DrawingController.prototype.renderFramePixel = function (col, row) {
this.renderer.drawPixel(col, row, this.frame, this.mainCanvas, this.dpi);
};
ns.DrawingController.prototype.renderOverlay = function () {
this.renderer.render(this.overlay, this.overlayCanvas, this.dpi);
};
ns.DrawingController.prototype.clearOverlay = function () {
this.overlay = ns.Frame.createEmptyFromFrame(this.frame);
this.overlayCanvas.getContext("2d").clearRect(0, 0, this.overlayCanvas.width, this.overlayCanvas.height);
};
ns.DrawingController.prototype.createMainCanvas = function () {
var mainCanvas = this.createCanvas();
mainCanvas.className = "canvas-main";
this.container.appendChild(mainCanvas);
return mainCanvas;
};
// For some tools, we need a fake canvas that overlay the drawing canvas. These tools are
// generally 'drap and release' based tools (stroke, selection, etc) and the fake canvas
// will help to visualize the tool interaction (without modifying the canvas).
ns.DrawingController.prototype.createOverlayCanvas = function () {
var overlayCanvas = this.createCanvas();
overlayCanvas.className = "canvas-overlay";
this.container.appendChild(overlayCanvas);
return overlayCanvas;
};
// For some tools, we need a fake canvas that overlay the drawing canvas. These tools are
// generally 'drap and release' based tools (stroke, selection, etc) and the fake canvas
// will help to visualize the tool interaction (without modifying the canvas).
ns.DrawingController.prototype.createCanvas = function () {
var width = this.frame.getWidth(),
height = this.frame.getHeight();
var canvas = document.createElement("canvas");
canvas.setAttribute("width", width * this.dpi);
canvas.setAttribute("height", height * this.dpi);
return canvas;
};
})();

53
js/rendering/Frame.js Normal file
View File

@ -0,0 +1,53 @@
(function () {
var ns = $.namespace("pskl.rendering");
ns.Frame = function (pixels) {
this.pixels = pixels;
};
ns.Frame.createEmpty = function (width, height) {
var pixels = []; //new Array(width);
for (var columnIndex=0; columnIndex < width; columnIndex++) {
var columnArray = [];
for(var heightIndex = 0; heightIndex < height; heightIndex++) {
columnArray.push(Constants.TRANSPARENT_COLOR);
}
pixels[columnIndex] = columnArray;
}
return new ns.Frame(pixels);
};
ns.Frame.createEmptyFromFrame = function (frame) {
return ns.Frame.createEmpty(frame.getWidth(), frame.getHeight());
};
ns.Frame.prototype.clone = function () {
var clone = ns.Frame.createEmptyFromFrame(this);
for (var col = 0 ; col < clone.getWidth() ; col++) {
for (var row = 0 ; row < clone.getHeight() ; row++) {
clone.setPixel(col, row, this.getPixel(col, row));
}
}
return clone;
};
ns.Frame.prototype.setPixel = function (col, row, color) {
this.pixels[col][row] = color;
};
ns.Frame.prototype.getPixel = function (col, row) {
return this.pixels[col][row];
};
ns.Frame.prototype.getWidth = function () {
return this.pixels.length;
};
ns.Frame.prototype.getHeight = function () {
return this.pixels[0].length;
};
ns.Frame.prototype.isInFrame = function (col, row) {
return col >= 0 && row >= 0 && col <= this.pixels.length && row <= this.pixels[0].length;
};
})();

View File

@ -3,17 +3,16 @@
ns.FrameRenderer = function () {}; ns.FrameRenderer = function () {};
ns.FrameRenderer.prototype.render = function (frame, canvas, dpi) { ns.FrameRenderer.prototype.render = function (frame, canvas, dpi) {
var color; for(var col = 0, width = frame.getWidth(); col < width; col++) {
for(var col = 0, num_col = frame.length; col < num_col; col++) { for(var row = 0, height = frame.getHeight(); row < height; row++) {
for(var row = 0, num_row = frame[col].length; row < num_row; row++) { this.drawPixel(col, row, frame, canvas, dpi);
color = frame[col][row];
this.drawPixelInCanvas(col, row, canvas, color, dpi);
} }
} }
}; };
ns.FrameRenderer.prototype.drawPixelInCanvas = function () { ns.FrameRenderer.prototype.drawPixel = function (col, row, frame, canvas, dpi) {
var context = canvas.getContext('2d'); var context = canvas.getContext('2d');
var color = frame.getPixel(col, row);
if(color == Constants.TRANSPARENT_COLOR) { if(color == Constants.TRANSPARENT_COLOR) {
context.clearRect(col * dpi, row * dpi, dpi, dpi); context.clearRect(col * dpi, row * dpi, dpi, dpi);
} }
@ -25,7 +24,5 @@
context.fillStyle = color; context.fillStyle = color;
context.fillRect(col * dpi, row * dpi, dpi, dpi); context.fillRect(col * dpi, row * dpi, dpi, dpi);
} }
};
}
})(); })();