Merge pull request #59 from grosbouddha/add-grid-for-real

Add grid for real
This commit is contained in:
Julian Descottes 2012-09-08 15:00:21 -07:00
commit 0163221ac9
9 changed files with 367 additions and 209 deletions

View File

@ -77,6 +77,13 @@
cursor: url(../img/tools/cursors/hand.png) 14 12, pointer; cursor: url(../img/tools/cursors/hand.png) 14 12, pointer;
} }
.tool-grid,
.tool-grid label,
.tool-grid input {
line-height: 2.5;
cursor: pointer;
}
.tool-icon.selected { .tool-icon.selected {
cursor: auto; cursor: auto;
background-color: #eee; background-color: #eee;

View File

@ -53,6 +53,13 @@
</li> </li>
</ul> </ul>
<ul class="tools-group">
<li class="tool-grid">
<input id="show-grid" type="checkbox"/>
<label for="show-grid">Show grid</label>
</li>
</ul>
</div> </div>
<div class='left-nav'> <div class='left-nav'>

View File

@ -12,5 +12,8 @@ var Constants = {
/* /*
* Default entry point for piskel web service: * Default entry point for piskel web service:
*/ */
PISKEL_SERVICE_URL: 'http://2.piskel-app.appspot.com' PISKEL_SERVICE_URL: 'http://2.piskel-app.appspot.com',
GRID_STROKE_WIDTH: 1,
GRID_STROKE_COLOR: "lightgray"
}; };

View File

@ -22,6 +22,15 @@ Events = {
*/ */
REFRESH: "REFRESH", REFRESH: "REFRESH",
/**
* Temporary event to bind the redraw of right preview film to the canvas.
* This redraw should be driven by model updates.
* TODO(vincz): Remove.
*/
REDRAW_PREVIEWFILM: "REDRAW_PREVIEWFILM",
GRID_DISPLAY_STATE_CHANGED: "GRID_DISPLAY_STATE_CHANGED",
/** /**
* The framesheet was reseted and is now probably drastically different. * The framesheet was reseted and is now probably drastically different.
* Number of frames, content of frames, color used for the palette may have changed. * Number of frames, content of frames, color used for the palette may have changed.

View File

@ -67,6 +67,17 @@ pskl.ToolSelector = (function() {
} }
}; };
/**
* Get state for the checkbox that control the display of the grid
* on the drawing canvas.
* @private
*/
var isShowGridChecked_ = function() {
var showGridCheckbox = $('#show-grid');
var isChecked = showGridCheckbox.is(':checked');
return isChecked;
};
return { return {
init: function() { init: function() {
@ -75,6 +86,13 @@ pskl.ToolSelector = (function() {
selectTool_(toolInstances.simplePen); selectTool_(toolInstances.simplePen);
// Activate listener on tool panel: // Activate listener on tool panel:
$("#tools-container").click(onToolIconClicked_); $("#tools-container").click(onToolIconClicked_);
// Show/hide the grid on drawing canvas:
$.publish(Events.GRID_DISPLAY_STATE_CHANGED, [isShowGridChecked_()])
$('#show-grid').change(function(evt) {
var checked = isShowGridChecked_();
$.publish(Events.GRID_DISPLAY_STATE_CHANGED, [checked])
});
} }
}; };
})(); })();

View File

@ -3,22 +3,203 @@
ns.DrawingController = function (frame, container, dpi) { ns.DrawingController = function (frame, container, dpi) {
this.dpi = dpi; this.dpi = dpi;
// TODO(vincz): Store user prefs in a localstorage string ?
var renderingOptions = { var renderingOptions = {
"dpi": dpi, "dpi": dpi,
"displayGrid": true // Retrieve from localsotrage config "hasGrid" : true
} };
// Public /**
* @public
*/
this.frame = frame; this.frame = frame;
this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(frame); // Type is frame
// Private /**
* @public
*/
this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(frame);
/**
* @private
*/
this.container = container; this.container = container;
this.renderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions, "drawing-canvas");
this.overlayRenderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions, "canvas-overlay"); this.renderer = new pskl.rendering.FrameRenderer(
this.container,
renderingOptions,
"drawing-canvas");
this.overlayRenderer = new pskl.rendering.FrameRenderer(
this.container,
renderingOptions,
"canvas-overlay");
this.renderer.init(this.frame); this.renderer.init(this.frame);
this.overlayRenderer.init(this.frame); this.overlayRenderer.init(this.frame);
// State of drawing controller:
this.isClicked = false;
this.isRightClicked = false;
this.previousMousemoveTime = 0;
this.currentToolBehavior = null;
this.primaryColor = Constants.DEFAULT_PEN_COLOR;
this.secondaryColor = Constants.TRANSPARENT_COLOR;
this.initMouseBehavior();
$.subscribe(Events.TOOL_SELECTED, $.proxy(function(evt, toolBehavior) {
console.log("Tool selected: ", toolBehavior);
this.currentToolBehavior = toolBehavior;
}, this));
$.subscribe(Events.COLOR_SELECTED, $.proxy(function(evt, color, isPrimary) {
console.log("Color selected: ", color);
if (isPrimary) {
this.primaryColor = color;
} else {
this.secondaryColor = color;
}
}, this));
};
ns.DrawingController.prototype.initMouseBehavior = function() {
var body = $('body');
this.container.mousedown($.proxy(this.onMousedown_, this));
this.container.mousemove($.proxy(this.onMousemove_, this));
body.mouseup($.proxy(this.onMouseup_, this));
// Deactivate right click:
this.container.contextmenu(this.onCanvasContextMenu_);
};
/**
* @private
*/
ns.DrawingController.prototype.onMousedown_ = function (event) {
this.isClicked = true;
if(event.button == 2) { // right click
this.isRightClicked = true;
$.publish(Events.CANVAS_RIGHT_CLICKED);
}
var spriteCoordinate = this.getSpriteCoordinate(event);
//console.log("mousedown: col: " + spriteCoordinate.col + " - row: " + spriteCoordinate.row);
this.currentToolBehavior.applyToolAt(
spriteCoordinate.col,
spriteCoordinate.row,
this.getCurrentColor_(),
this
);
$.publish(Events.LOCALSTORAGE_REQUEST);
};
/**
* @private
*/
ns.DrawingController.prototype.onMousemove_ = function (event) {
var currentTime = new Date().getTime();
// Throttling of the mousemove event:
if ((currentTime - this.previousMousemoveTime) > 40 ) {
var spriteCoordinate = this.getSpriteCoordinate(event);
if (this.isClicked) {
this.currentToolBehavior.moveToolAt(
spriteCoordinate.col,
spriteCoordinate.row,
this.getCurrentColor_(),
this
);
//console.log("mousemove: col: " + spriteCoordinate.col + " - row: " + spriteCoordinate.row);
// 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,
// you don't need to draw anything when mousemoving and you request useless localStorage.
$.publish(Events.LOCALSTORAGE_REQUEST);
} else {
// debug mode to see the selected pixel
// this.clearOverlay();
// this.overlayFrame.setPixel( spriteCoordinate.col,spriteCoordinate.row, "#ff0000");
// this.renderOverlay();
}
this.previousMousemoveTime = currentTime;
}
};
/**
* @private
*/
ns.DrawingController.prototype.onMouseup_ = function (event) {
if(this.isClicked || this.isRightClicked) {
// A mouse button was clicked on the drawing canvas before this mouseup event,
// the user was probably drawing on the canvas.
// Note: The mousemove movement (and the mouseup) may end up outside
// of the drawing canvas.
if(this.isRightClicked) {
$.publish(Events.CANVAS_RIGHT_CLICK_RELEASED);
}
this.isClicked = false;
this.isRightClicked = false;
var spriteCoordinate = this.getSpriteCoordinate(event);
//console.log("mousemove: col: " + spriteCoordinate.col + " - row: " + spriteCoordinate.row);
this.currentToolBehavior.releaseToolAt(
spriteCoordinate.col,
spriteCoordinate.row,
this.getCurrentColor_(),
this
);
$.publish(Events.TOOL_RELEASED);
// TODO: Remove that when we have the centralized redraw loop
$.publish(Events.REDRAW_PREVIEWFILM);
}
},
/**
* @private
*/
ns.DrawingController.prototype.getRelativeCoordinates = function (clientX, clientY) {
var canvasPageOffset = this.container.offset();
return {
x : clientX - canvasPageOffset.left,
y : clientY - canvasPageOffset.top
};
};
/**
* @private
*/
ns.DrawingController.prototype.getSpriteCoordinate = function(event) {
var coords = this.getRelativeCoordinates(event.clientX, event.clientY);
return this.renderer.convertPixelCoordinatesIntoSpriteCoordinate(coords);
};
/**
* @private
*/
ns.DrawingController.prototype.getCurrentColor_ = function () {
if(this.isRightClicked) {
return this.secondaryColor;
} else {
return this.primaryColor;
}
};
/**
* @private
*/
ns.DrawingController.prototype.onCanvasContextMenu_ = function (event) {
event.preventDefault();
event.stopPropagation();
event.cancelBubble = true;
return false;
}; };
ns.DrawingController.prototype.updateDPI = function (newDPI) { ns.DrawingController.prototype.updateDPI = function (newDPI) {

View File

@ -5,6 +5,10 @@
this.dpi = dpi; this.dpi = dpi;
this.framesheet = framesheet; this.framesheet = framesheet;
this.container = container; this.container = container;
$.subscribe(Events.REDRAW_PREVIEWFILM, $.proxy(function(evt) {
this.createPreviews()
}, this));
}; };
ns.PreviewFilmController.prototype.init = function() { ns.PreviewFilmController.prototype.init = function() {
@ -28,7 +32,7 @@
for (var i = 0, l = frameCount; i < l ; i++) { for (var i = 0, l = frameCount; i < l ; i++) {
this.container.append(this.createInterstitialTile_(i)); this.container.append(this.createInterstitialTile_(i));
this.container.append(this.createPreviewTile_(i)); this.container.append(this.createPreviewTile_(i, this.framesheet));
} }
this.container.append(this.createInterstitialTile_(frameCount)); this.container.append(this.createInterstitialTile_(frameCount));
@ -142,10 +146,8 @@
* @private * @private
* TODO(vincz): clean this giant rendering function & remove listeners. * TODO(vincz): clean this giant rendering function & remove listeners.
*/ */
ns.PreviewFilmController.prototype.createPreviewTile_ = function(tileNumber) { ns.PreviewFilmController.prototype.createPreviewTile_ = function(tileNumber, framesheet) {
var currentFrame = this.framesheet.getFrameByIndex(tileNumber); var currentFrame = this.framesheet.getFrameByIndex(tileNumber);
//var width = frame.getWidth() * this.dpi,
// height = frame.getHeight() * this.dpi;
var previewTileRoot = document.createElement("li"); var previewTileRoot = document.createElement("li");
var classname = "preview-tile"; var classname = "preview-tile";
@ -158,18 +160,10 @@
var canvasContainer = document.createElement("div"); var canvasContainer = document.createElement("div");
canvasContainer.className = "canvas-container"; canvasContainer.className = "canvas-container";
//canvasContainer.setAttribute('style', 'width:' + width + 'px; height:' + height + 'px;');
var canvasBackground = document.createElement("div"); var canvasBackground = document.createElement("div");
canvasBackground.className = "canvas-background"; canvasBackground.className = "canvas-background";
canvasContainer.appendChild(canvasBackground); canvasContainer.appendChild(canvasBackground);
/*
var canvasPreview = document.createElement("canvas");
canvasPreview.className = "canvas tile-view"
canvasPreview.setAttribute('width', width);
canvasPreview.setAttribute('height', height);
*/
previewTileRoot.addEventListener('click', function(evt) { previewTileRoot.addEventListener('click', function(evt) {
// has not class tile-action: // has not class tile-action:
@ -183,7 +177,9 @@
canvasPreviewDuplicateAction.innerHTML = "dup" canvasPreviewDuplicateAction.innerHTML = "dup"
canvasPreviewDuplicateAction.addEventListener('click', function(evt) { canvasPreviewDuplicateAction.addEventListener('click', function(evt) {
piskel.duplicateFrame(tileNumber); framesheet.duplicateFrameByIndex(tileNumber);
$.publish(Events.LOCALSTORAGE_REQUEST); // Should come from model
$.publish('SET_ACTIVE_FRAME', [tileNumber + 1]);
}); });
//this.renderer.render(this.framesheet.getFrameByIndex(tileNumber), canvasPreview); //this.renderer.render(this.framesheet.getFrameByIndex(tileNumber), canvasPreview);
@ -191,7 +187,7 @@
// TODO(vincz): Eventually optimize this part by not recreating a FrameRenderer. Note that the real optim // TODO(vincz): Eventually optimize this part by not recreating a FrameRenderer. Note that the real optim
// is to make this update function (#createPreviewTile) less aggressive. // is to make this update function (#createPreviewTile) less aggressive.
var renderingOptions = {"dpi": this.dpi }; var renderingOptions = {"dpi": this.dpi };
var currentFrameRenderer = new pskl.rendering.FrameRenderer(canvasContainer, renderingOptions, "tile-view"); var currentFrameRenderer = new pskl.rendering.FrameRenderer($(canvasContainer), renderingOptions, "tile-view");
currentFrameRenderer.init(currentFrame); currentFrameRenderer.init(currentFrame);
previewTileRoot.appendChild(canvasContainer); previewTileRoot.appendChild(canvasContainer);
@ -202,7 +198,9 @@
canvasPreviewDeleteAction.className = "tile-action" canvasPreviewDeleteAction.className = "tile-action"
canvasPreviewDeleteAction.innerHTML = "del" canvasPreviewDeleteAction.innerHTML = "del"
canvasPreviewDeleteAction.addEventListener('click', function(evt) { canvasPreviewDeleteAction.addEventListener('click', function(evt) {
piskel.removeFrame(tileNumber); framesheet.removeFrameByIndex(tileNumber);
$.publish(Events.FRAMESHEET_RESET);
$.publish(Events.LOCALSTORAGE_REQUEST); // Should come from model
}); });
previewTileRoot.appendChild(canvasPreviewDeleteAction); previewTileRoot.appendChild(canvasPreviewDeleteAction);
} }

View File

@ -24,23 +24,8 @@ $.namespace("pskl");
// Animated canvas preview: // Animated canvas preview:
previewAnimationCanvasDpi = 8, previewAnimationCanvasDpi = 8,
// DOM references:
drawingAreaContainer,
drawingAreaCanvas,
previewCanvas,
// States:
isClicked = false,
isRightClicked = false,
activeFrameIndex = -1, activeFrameIndex = -1,
animIndex = 0,
primaryColor = Constants.DEFAULT_PEN_COLOR,
secondaryColor = Constants.TRANSPARENT_COLOR,
currentFrame = null; currentFrame = null;
currentToolBehavior = null,
previousMousemoveTime = 0;
/** /**
* Main application controller * Main application controller
@ -56,7 +41,7 @@ $.namespace("pskl");
this.drawingController = new pskl.controller.DrawingController( this.drawingController = new pskl.controller.DrawingController(
frameSheet.getFrameByIndex(0), frameSheet.getFrameByIndex(0),
$('#drawing-canvas-container')[0], $('#drawing-canvas-container'),
drawingCanvasDpi drawingCanvasDpi
); );
@ -64,7 +49,7 @@ $.namespace("pskl");
this.animationController = new pskl.controller.AnimatedPreviewController( this.animationController = new pskl.controller.AnimatedPreviewController(
frameSheet, frameSheet,
$('#preview-canvas-container')[0], $('#preview-canvas-container'),
previewAnimationCanvasDpi previewAnimationCanvasDpi
); );
@ -91,6 +76,14 @@ $.namespace("pskl");
this.finishInit(); this.finishInit();
pskl.LocalStorageService.displayRestoreNotification(); pskl.LocalStorageService.displayRestoreNotification();
} }
$.subscribe('SET_ACTIVE_FRAME', function(evt, frameId) {
piskel.setActiveFrameAndRedraw(frameId);
});
$.subscribe('FRAMESHEET_RESET', function(evt, frameId) {
piskel.redraw();
});
}, },
/** /**
@ -112,7 +105,7 @@ $.namespace("pskl");
* @private * @private
*/ */
calculateDPIsForDrawingCanvas_ : function() { calculateDPIsForDrawingCanvas_ : function() {
var availableViewportHeight = $('.main-panel').height(), var availableViewportHeight = $('.main-panel').height() - 50,
availableViewportWidth = $('.main-panel').width(), availableViewportWidth = $('.main-panel').width(),
previewHeight = $(".preview-container").height(), previewHeight = $(".preview-container").height(),
previewWidth = $(".preview-container").width(); previewWidth = $(".preview-container").width();
@ -142,27 +135,12 @@ $.namespace("pskl");
finishInit : function () { finishInit : function () {
$.subscribe(Events.TOOL_SELECTED, function(evt, toolBehavior) {
console.log("Tool selected: ", toolBehavior);
currentToolBehavior = toolBehavior;
});
$.subscribe(Events.COLOR_SELECTED, function(evt, color, isPrimary) {
console.log("Color selected: ", color);
if (isPrimary) {
primaryColor = color;
} else {
secondaryColor = color;
}
});
$.subscribe(Events.REFRESH, function() { $.subscribe(Events.REFRESH, function() {
piskel.setActiveFrameAndRedraw(0); piskel.setActiveFrameAndRedraw(0);
}); });
// TODO: Move this into their service or behavior files:
this.initDrawingArea();
pskl.ToolSelector.init(); pskl.ToolSelector.init();
pskl.Palette.init(frameSheet); pskl.Palette.init(frameSheet);
}, },
@ -226,132 +204,6 @@ $.namespace("pskl");
return frameSheet.getFrameByIndex(activeFrameIndex); return frameSheet.getFrameByIndex(activeFrameIndex);
}, },
initDrawingArea : function() {
drawingAreaContainer = $('#drawing-canvas-container')[0];
document.body.addEventListener('mouseup', this.onMouseup.bind(this));
drawingAreaContainer.addEventListener('mousedown', this.onMousedown.bind(this));
drawingAreaContainer.addEventListener('mousemove', this.onMousemove.bind(this));
document.body.addEventListener('contextmenu', this.onCanvasContextMenu);
},
removeFrame: function(frameIndex) {
frameSheet.removeFrameByIndex(frameIndex);
var activeFrameIndex = frameIndex ? frameIndex - 1 : 0;
this.setActiveFrameAndRedraw(activeFrameIndex);
},
duplicateFrame: function(frameIndex) {
frameSheet.duplicateFrameByIndex(frameIndex);
this.setActiveFrameAndRedraw(frameIndex + 1);
},
getCurrentColor : function () {
if(isRightClicked) {
return secondaryColor;
} else {
return primaryColor;
}
},
onMousedown : function (event) {
isClicked = true;
if(event.button == 2) { // right click
isRightClicked = true;
$.publish(Events.CANVAS_RIGHT_CLICKED);
}
var spriteCoordinate = this.getSpriteCoordinate(event);
currentToolBehavior.applyToolAt(
spriteCoordinate.col,
spriteCoordinate.row,
this.getCurrentColor(),
this.drawingController
);
$.publish(Events.LOCALSTORAGE_REQUEST);
},
onMousemove : function (event) {
var currentTime = new Date().getTime();
// Throttling of the mousemove event:
if ((currentTime - previousMousemoveTime) > 40 ) {
var spriteCoordinate = this.getSpriteCoordinate(event);
if (isClicked) {
currentToolBehavior.moveToolAt(
spriteCoordinate.col,
spriteCoordinate.row,
this.getCurrentColor(),
this.drawingController
);
// 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,
// you don't need to draw anything when mousemoving and you request useless localStorage.
$.publish(Events.LOCALSTORAGE_REQUEST);
} else {
// debug mode to see the selected pixel
// this.drawingController.clearOverlay();
// this.drawingController.overlay.setPixel( spriteCoordinate.col,spriteCoordinate.row, "#ff0000");
// this.drawingController.renderOverlay();
}
previousMousemoveTime = currentTime;
}
},
onMouseup : function (event) {
if(isClicked || isRightClicked) {
// A mouse button was clicked on the drawing canvas before this mouseup event,
// the user was probably drawing on the canvas.
// Note: The mousemove movement (and the mouseup) may end up outside
// of the drawing canvas.
if(isRightClicked) {
$.publish(Events.CANVAS_RIGHT_CLICK_RELEASED);
}
isClicked = false;
isRightClicked = false;
var spriteCoordinate = this.getSpriteCoordinate(event);
currentToolBehavior.releaseToolAt(
spriteCoordinate.col,
spriteCoordinate.row,
this.getCurrentColor(),
this.drawingController
);
$.publish(Events.TOOL_RELEASED);
// TODO: Remove that when we have the centralized redraw loop
this.previewsController.createPreviews();
}
},
onCanvasContextMenu : function (event) {
event.preventDefault();
event.stopPropagation();
event.cancelBubble = true;
return false;
},
getRelativeCoordinates : function (x, y) {
var canvasRect = $(".drawing-canvas")[0].getBoundingClientRect();
return {
x : x - canvasRect.left,
y : y - canvasRect.top
}
},
getSpriteCoordinate : function(event) {
var coord = this.getRelativeCoordinates(event.x, event.y);
var coords = this.getRelativeCoordinates(event.clientX, event.clientY);
return {
"col" : (coords.x - coords.x%drawingCanvasDpi) / drawingCanvasDpi,
"row" : (coords.y - coords.y%drawingCanvasDpi) / drawingCanvasDpi
}
},
// TODO(julz): Create package ? // TODO(julz): Create package ?
storeSheet : function (event) { storeSheet : function (event) {
// TODO Refactor using jquery ? // TODO Refactor using jquery ?

View File

@ -1,29 +1,42 @@
(function () { (function () {
var ns = $.namespace("pskl.rendering"); var ns = $.namespace("pskl.rendering");
this.dpi = null;
this.canvas = null;
ns.FrameRenderer = function (container, renderingOptions, className) { ns.FrameRenderer = function (container, renderingOptions, className) {
this.defaultRenderingOptions = {
"hasGrid" : false
};
renderingOptions = $.extend(true, {}, this.defaultRenderingOptions, renderingOptions);
if(container == undefined) { if(container == undefined) {
throw "Bad FrameRenderer initialization. <container> undefined."; throw "Bad FrameRenderer initialization. <container> undefined.";
} }
this.container = container;
if(renderingOptions == undefined || renderingOptions.dpi == undefined || isNaN(dpi)) { if(isNaN(renderingOptions.dpi)) {
throw "Bad FrameRenderer initialization. <dpi> not well defined."; throw "Bad FrameRenderer initialization. <dpi> not well defined.";
} }
this.displayGrid = !!renderingOptions.displayGrid; this.container = container;
this.dpi = renderingOptions.dpi; this.dpi = renderingOptions.dpi;
this.className = className; this.className = className;
this.canvas = null;
this.hasGrid = renderingOptions.hasGrid;
this.gridStrokeWidth = 0;
this.lastRenderedFrame = null;
// Flag to know if the config was altered // Flag to know if the config was altered
this.canvasConfigDirty = true; this.canvasConfigDirty = true;
if(this.hasGrid) {
$.subscribe(Events.GRID_DISPLAY_STATE_CHANGED, $.proxy(this.showGrid, this));
}
}; };
ns.FrameRenderer.prototype.init = function (frame) { ns.FrameRenderer.prototype.init = function (frame) {
this.render(frame); this.render(frame);
this.lastRenderedFrame = frame;
}; };
ns.FrameRenderer.prototype.updateDPI = function (newDPI) { ns.FrameRenderer.prototype.updateDPI = function (newDPI) {
@ -31,19 +44,34 @@
this.canvasConfigDirty = true; this.canvasConfigDirty = true;
}; };
ns.FrameRenderer.prototype.render = function (frame) { ns.FrameRenderer.prototype.showGrid = function (evt, show) {
for(var col = 0, width = frame.getWidth(); col < width; col++) {
for(var row = 0, height = frame.getHeight(); row < height; row++) { this.gridStrokeWidth = 0;
this.drawPixel(col, row, frame, this.getCanvas_(frame), this.dpi); if(show) {
this.gridStrokeWidth = Constants.GRID_STROKE_WIDTH;
} }
this.canvasConfigDirty = true;
if(this.lastRenderedFrame) {
this.render(this.lastRenderedFrame);
} }
}; };
ns.FrameRenderer.prototype.render = function (frame) {
for(var col = 0, width = frame.getWidth(); col < width; col++) {
for(var row = 0, height = frame.getHeight(); row < height; row++) {
this.drawPixel(col, row, frame, this.getCanvas_(frame, col, row), this.dpi);
}
}
this.lastRenderedFrame = frame;
};
ns.FrameRenderer.prototype.drawPixel = function (col, row, frame) { ns.FrameRenderer.prototype.drawPixel = function (col, row, frame) {
var context = this.getCanvas_(frame).getContext('2d'); var context = this.getCanvas_(frame, col, row).getContext('2d');
var color = frame.getPixel(col, row); var color = frame.getPixel(col, row);
if(color == Constants.TRANSPARENT_COLOR) { if(color == Constants.TRANSPARENT_COLOR) {
context.clearRect(col * this.dpi, row * this.dpi, this.dpi, this.dpi); context.clearRect(this.getFrameY_(col), this.getFrameY_(row), this.dpi, this.dpi);
} }
else { else {
if(color != Constants.SELECTION_TRANSPARENT_COLOR) { if(color != Constants.SELECTION_TRANSPARENT_COLOR) {
@ -51,37 +79,92 @@
$.publish(Events.COLOR_USED, [color]); $.publish(Events.COLOR_USED, [color]);
} }
context.fillStyle = color; context.fillStyle = color;
context.fillRect(col * this.dpi, row * this.dpi, this.dpi, this.dpi); context.fillRect(this.getFrameY_(col), this.getFrameY_(row), this.dpi, this.dpi);
} }
this.lastRenderedFrame = frame;
}; };
ns.FrameRenderer.prototype.clear = function (col, row, frame) { ns.FrameRenderer.prototype.clear = function (col, row, frame) {
var canvas = this.getCanvas_(frame) var canvas = this.getCanvas_(frame, col, row)
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height); canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
}; };
/**
* Transform a screen pixel-based coordinate (relative to the top-left corner of the rendered
* frame) into a sprite coordinate in column and row.
* @public
*/
ns.FrameRenderer.prototype.convertPixelCoordinatesIntoSpriteCoordinate = function(coords) {
var cellSize = this.dpi + this.gridStrokeWidth;
return {
"col" : (coords.x - coords.x % cellSize) / cellSize,
"row" : (coords.y - coords.y % cellSize) / cellSize
};
};
/**
* @private
*/
ns.FrameRenderer.prototype.getFrameX_ = function(col) {
return col * this.dpi + ((col - 1) * this.gridStrokeWidth);
};
/**
* @private
*/
ns.FrameRenderer.prototype.getFrameY_ = function(row) {
return row * this.dpi + ((row - 1) * this.gridStrokeWidth);
};
/**
* @private
*/
ns.FrameRenderer.prototype.drawGrid_ = function(canvas, width, height, col, row) {
var ctx = canvas.getContext("2d");
ctx.lineWidth = Constants.GRID_STROKE_WIDTH;
ctx.strokeStyle = Constants.GRID_STROKE_COLOR;
for(var c=1; c < col; c++) {
ctx.moveTo(this.getFrameX_(c), 0);
ctx.lineTo(this.getFrameX_(c), height);
ctx.stroke();
}
for(var r=1; r < row; r++) {
ctx.moveTo(0, this.getFrameY_(r));
ctx.lineTo(width, this.getFrameY_(r));
ctx.stroke();
}
};
/** /**
* @private * @private
*/ */
ns.FrameRenderer.prototype.getCanvas_ = function (frame) { ns.FrameRenderer.prototype.getCanvas_ = function (frame) {
if(this.canvasConfigDirty) { if(this.canvasConfigDirty) {
$(this.canvas).remove(); $(this.canvas).remove();
var width = frame.getWidth(),
height = frame.getHeight(); var col = frame.getWidth(),
row = frame.getHeight();
var canvas = document.createElement("canvas"); var canvas = document.createElement("canvas");
canvas.setAttribute("width", width * this.dpi);
canvas.setAttribute("height", height * this.dpi);
var pixelWidth = col * this.dpi + this.gridStrokeWidth * (col - 1);
var pixelHeight = row * this.dpi + this.gridStrokeWidth * (row - 1);
canvas.setAttribute("width", pixelWidth);
canvas.setAttribute("height", pixelHeight);
var canvasClassname = "canvas"; var canvasClassname = "canvas";
if(this.className) { if(this.className) {
canvasClassname += " " + this.className; canvasClassname += " " + this.className;
} }
canvas.setAttribute("class", canvasClassname); canvas.setAttribute("class", canvasClassname);
this.container.append(canvas);
if(this.gridStrokeWidth > 0) {
this.drawGrid_(canvas, pixelWidth, pixelHeight, col, row);
}
this.canvas = canvas; this.canvas = canvas;
this.container.appendChild(this.canvas);
this.canvasConfigDirty = false; this.canvasConfigDirty = false;
} }
return this.canvas; return this.canvas;