Merge branch 'master' of git://github.com/juliandescottes/piskel

This commit is contained in:
Patrick Brosset 2012-09-09 00:09:35 +02:00
commit ed177d92e6
25 changed files with 4021 additions and 384 deletions

View File

@ -0,0 +1,63 @@
.preview-list {
list-style-type: none;
}
.preview-tile {
padding : 10px;
overflow: hidden;
background-color: gray;
}
.preview-tile .canvas-container {
float: left;
}
.preview-tile .tile-view {
float: left;
border: blue 1px solid;
}
.preview-tile .tile-action {
display: none;
float: right;
}
.preview-tile:hover .tile-action {
display: block;
}
.preview-tile:hover {
background-color: lightgray;
}
.preview-tile.selected {
background-color: lightyellow;
}
.preview-tile.ui-draggable-dragging {
opacity: 0.3;
}
.preview-tile.droppable-active {
background-color: pink;
}
.interstitial-tile.droppable-hover-active {
background-color: purple;
}
.preview-tile.droppable-hover-active {
background-color: yellow;
}
.interstitial-tile {
visibility: hidden;
background-color: blue;
height: 10px;
}
.show-interstitial-tiles .interstitial-tile {
visibility: visible;
}

View File

@ -52,41 +52,6 @@
display : inline-block;
}
#preview-list {
list-style-type: none;
}
.preview-tile {
padding : 10px;
overflow: hidden;
background-color: gray;
}
.preview-tile .canvas-container {
float: left;
}
.preview-tile .tile-view {
float: left;
border: blue 1px solid;
}
.preview-tile .tile-action {
display: none;
float: right;
}
.preview-tile:hover .tile-action {
display: block;
}
.preview-tile:hover {
background-color: lightgray;
}
#preview-list .preview-tile.selected {
background-color: lightyellow;
}
.canvas-container {
position: relative;
@ -108,10 +73,7 @@
}
.drawing-canvas {
position: absolute;
top: 0;
left: 0;
z-index: 1;
float: left;
}
.canvas-overlay {

View File

@ -9,6 +9,7 @@
.tool-icon {
float: left;
cursor : pointer;
width: 30px;
height: 30px;
background-color: transparent;
@ -44,47 +45,70 @@
background-image: url(../img/tools/icons/rectangle.png);
}
.tool-icon.tool-move {
background-image: url(../img/tools/icons/hand.png);
}
/*.tool-icon.tool-palette {
background-image: url(../img/tools/icons/color-palette.png);
}*/
.tool-paint-bucket .drawing-canvas-container:hover {
cursor: url(../img/tools/cursors/paint-bucket.png) 18 17, pointer;
cursor: url(../img/tools/cursors/paint-bucket.png) 14 12, pointer;
}
.tool-pen .drawing-canvas-container:hover {
cursor: url(../img/tools/cursors/pen.png) 7 21, pointer;
cursor: url(../img/tools/cursors/pen.png) 2 21, pointer;
}
.tool-eraser .drawing-canvas-container:hover {
cursor: url(../img/tools/cursors/eraser.png) 5 21, pointer;
cursor: url(../img/tools/cursors/eraser.png) 2 21, pointer;
}
.tool-stroke .drawing-canvas-container:hover {
cursor: url(../img/tools/cursors/pen.png) 5 21, pointer;
cursor: url(../img/tools/cursors/pen.png) 2 21, pointer;
}
.tool-rectangle .drawing-canvas-container:hover {
cursor: url(../img/tools/cursors/rectangle.png) 4 21, pointer;
}
.tool-move .drawing-canvas-container:hover {
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 {
cursor: auto;
background-color: #eee;
}
.tool-icon:hover {
cursor: pointer;
background-color: #eee;
}
.tool-color-picker {
padding: 5px 0 0 5px;
cursor : default;
}
.tool-color-picker input {
width: 12px; height: 12px;
width: 8px; height: 8px;
border: 1px solid black;
padding: 1px;
background: white;
margin: 7px 0 0 7px;
cursor: pointer;
position : relative;
}
#secondary-color-picker {
top : 8px;
}
.tool-palette {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 603 B

After

Width:  |  Height:  |  Size: 656 B

BIN
img/tools/cursors/hand.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 672 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 603 B

After

Width:  |  Height:  |  Size: 656 B

BIN
img/tools/icons/hand.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 672 B

View File

@ -12,6 +12,7 @@
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/tools.css">
<link rel="stylesheet" href="css/preview-film-section.css">
</head>
@ -30,6 +31,7 @@
<li class="tool-icon tool-paint-bucket" data-tool-id="tool-paint-bucket" title="Bucket tool"></li>
<li class="tool-icon tool-stroke" data-tool-id="tool-stroke" title="Stroke tool"></li>
<li class="tool-icon tool-rectangle" data-tool-id="tool-rectangle" title="Rectangle tool"></li>
<li class="tool-icon tool-move" data-tool-id="tool-move" title="Move tool"></li>
</ul>
<ul class="tools-group">
@ -40,6 +42,7 @@
</li>
<li class="tool-icon tool-color-picker">
<input id="color-picker" class="color {hash:true}" type="text" value="" />
<input id="secondary-color-picker" class="color {hash:true}" type="text" value="" />
</li>
</ul>
@ -49,12 +52,19 @@
<span id="display-fps">12 fps</span>
</li>
</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 class='left-nav'>
<!-- List of frames: -->
<ul id="preview-list"></ul>
<ul class="preview-list" id="preview-list"></ul>
</div>
<div class='main-panel'>
@ -74,6 +84,7 @@
<!-- Core libraries: -->
<script src="js/lib/jquery-1.8.0.js"></script>
<script src="js/lib/jquery-ui-1.8.23.custom.js"></script>
<script src="js/lib/pubsub.js"></script>
<!-- Application wide configuration -->
@ -87,11 +98,12 @@
<!-- Application libraries-->
<script src="js/model/Frame.js"></script>
<script src="js/model/FrameSheet.js"></script>
<script src="js/rendering/FrameRenderer.js"></script>
<script src="js/controller/DrawingController.js"></script>
<script src="js/controller/PreviewFilmController.js"></script>
<script src="js/controller/AnimatedPreviewController.js"></script>
<script src="js/rendering/FrameRenderer.js"></script>
<script src="js/LocalStorageService.js"></script>
<script src="js/HistoryManager.js"></script>
<script src="js/Palette.js"></script>
<script src="js/Notification.js"></script>
<script src="js/drawingtools/BaseTool.js"></script>
@ -100,6 +112,7 @@
<script src="js/drawingtools/Stroke.js"></script>
<script src="js/drawingtools/PaintBucket.js"></script>
<script src="js/drawingtools/Rectangle.js"></script>
<script src="js/drawingtools/Move.js"></script>
<script src="js/ToolSelector.js"></script>
<!-- Application controller and initialization -->

View File

@ -12,5 +12,8 @@ var Constants = {
/*
* 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

@ -1,6 +1,7 @@
Events = {
TOOL_SELECTED : "TOOL_SELECTED",
TOOL_RELEASED : "TOOL_RELEASED",
COLOR_SELECTED: "COLOR_SELECTED",
COLOR_USED: "COLOR_USED",
@ -21,6 +22,15 @@ Events = {
*/
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.
* Number of frames, content of frames, color used for the palette may have changed.

40
js/HistoryManager.js Normal file
View File

@ -0,0 +1,40 @@
(function () {
var ns = $.namespace("pskl");
ns.HistoryManager = function () {};
ns.HistoryManager.prototype.init = function () {
document.body.addEventListener('keyup', this.onKeyup.bind(this));
$.subscribe(Events.TOOL_RELEASED, this.saveState.bind(this));
};
ns.HistoryManager.prototype.saveState = function () {
piskel.getCurrentFrame().saveState();
};
ns.HistoryManager.prototype.onKeyup = function (evt) {
if (evt.ctrlKey && evt.keyCode == 90) { // CTRL + Z
this.undo();
}
if (evt.ctrlKey && evt.keyCode == 89) { // CTRL+ Y
this.redo();
}
};
ns.HistoryManager.prototype.undo = function () {
piskel.getCurrentFrame().loadPreviousState();
this.redraw();
};
ns.HistoryManager.prototype.redo = function () {
piskel.getCurrentFrame().loadNextState();
this.redraw();
};
ns.HistoryManager.prototype.redraw = function () {
piskel.drawingController.renderFrame();
piskel.previewsController.createPreviews();
};
ns.HistoryManager = new ns.HistoryManager();
})();

View File

@ -14,9 +14,9 @@ pskl.Palette = (function() {
/**
* @private
*/
var onPickerChange_ = function(evt) {
var onPickerChange_ = function(evt, isPrimary) {
var inputPicker = $(evt.target);
$.publish(Events.COLOR_SELECTED, [inputPicker.val()]);
$.publish(Events.COLOR_SELECTED, [inputPicker.val(), evt.data.isPrimary]);
};
/**
@ -36,7 +36,7 @@ pskl.Palette = (function() {
* @private
*/
var addColorToPalette_ = function (color) {
if (paletteColors.indexOf(color) == -1) {
if (paletteColors.indexOf(color) == -1 && color != Constants.TRANSPARENT_COLOR) {
var colorEl = document.createElement("li");
colorEl.className = "palette-color";
colorEl.setAttribute("data-color", color);
@ -52,8 +52,17 @@ pskl.Palette = (function() {
*/
var onPaletteColorClick_ = function (event) {
var selectedColor = $(event.target).data("color");
var colorPicker = $('#color-picker');
if (selectedColor == Constants.TRANSPARENT_COLOR) {
if (event.which == 1) { // left button
updateColorPicker(selectedColor, $('#color-picker'));
$.publish(Events.COLOR_SELECTED, [selectedColor, true]);
} else if (event.which == 3) { // right button
updateColorPicker(selectedColor, $('#secondary-color-picker'));
$.publish(Events.COLOR_SELECTED, [selectedColor, false]);
}
};
var updateColorPicker = function (color, colorPicker) {
if (color == Constants.TRANSPARENT_COLOR) {
// We can set the current palette color to transparent.
// You can then combine this transparent color with an advanced
// tool for customized deletions.
@ -64,12 +73,11 @@ pskl.Palette = (function() {
// We set its background to white and insert the
// string "TRANSPARENT" to mimic this state:
colorPicker[0].color.fromString("#fff");
colorPicker.val("TRANSPARENT");
colorPicker.val(Constants.TRANSPARENT_COLOR);
} else {
colorPicker[0].color.fromString(selectedColor);
colorPicker[0].color.fromString(color);
}
$.publish(Events.COLOR_SELECTED, [selectedColor])
};
}
return {
init: function(framesheet) {
@ -83,15 +91,20 @@ pskl.Palette = (function() {
createPalette_(framesheet.getUsedColors());
});
paletteRoot.click(onPaletteColorClick_);
$.subscribe(Events.COLOR_USED, function(evt, color) {
paletteRoot.mouseup(onPaletteColorClick_);
$.subscribe(Events.COLOR_SELECTED, function(evt, color) {
addColorToPalette_(color);
});
// Initialize colorpicker:
var colorPicker = $('#color-picker');
colorPicker.val(Constants.DEFAULT_PEN_COLOR);
colorPicker.change(onPickerChange_);
colorPicker.change({isPrimary : true}, onPickerChange_);
var secondaryColorPicker = $('#secondary-color-picker');
secondaryColorPicker.val(Constants.TRANSPARENT_COLOR);
secondaryColorPicker.change({isPrimary : false}, onPickerChange_);
}
};

View File

@ -14,7 +14,8 @@ pskl.ToolSelector = (function() {
"eraser" : new pskl.drawingtools.Eraser(),
"paintBucket" : new pskl.drawingtools.PaintBucket(),
"stroke" : new pskl.drawingtools.Stroke(),
"rectangle" : new pskl.drawingtools.Rectangle()
"rectangle" : new pskl.drawingtools.Rectangle(),
"move" : new pskl.drawingtools.Move()
};
var currentSelectedTool = toolInstances.simplePen;
var previousSelectedTool = toolInstances.simplePen;
@ -66,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 {
init: function() {
@ -75,16 +87,11 @@ pskl.ToolSelector = (function() {
// Activate listener on tool panel:
$("#tools-container").click(onToolIconClicked_);
// Special right click handlers (select the eraser tool)
$.subscribe(Events.CANVAS_RIGHT_CLICKED, function() {
previousSelectedTool = currentSelectedTool;
currentSelectedTool = toolInstances.eraser;
$.publish(Events.TOOL_SELECTED, [currentSelectedTool]);
});
$.subscribe(Events.CANVAS_RIGHT_CLICK_RELEASED, function() {
currentSelectedTool = previousSelectedTool;
$.publish(Events.TOOL_SELECTED, [currentSelectedTool]);
// 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

@ -1,36 +1,27 @@
(function () {
var ns = $.namespace("pskl.controller");
ns.AnimatedPreviewController = function (framesheet, container, dpi) {
this.dpi = dpi;
this.framesheet = framesheet;
this.container = container;
this.animIndex = 0;
this.fps = parseInt($("#preview-fps")[0].value, 10);
this.renderer = new pskl.rendering.FrameRenderer();
var renderingOptions = {
"dpi": dpi
};
this.renderer = new pskl.rendering.FrameRenderer(this.container, renderingOptions);
};
ns.AnimatedPreviewController.prototype.init = function () {
this.initDom();
this.renderer.init(this.framesheet.getFrameByIndex(this.animIndex));
this.startAnimationTimer();
};
ns.AnimatedPreviewController.prototype.initDom = function () {
var frame = this.framesheet.getFrameByIndex(0);
var height = frame.getHeight() * this.dpi,
width = frame.getWidth() * this.dpi;
previewCanvas = document.createElement('canvas');
previewCanvas.className = 'canvas';
this.container.setAttribute('style', 'width:' + width + 'px; height:' + height + 'px;');
previewCanvas.setAttribute('width', width);
previewCanvas.setAttribute('height', height);
this.container.appendChild(previewCanvas);
this.previewCanvas = previewCanvas;
$("#preview-fps")[0].addEventListener('change', this.onFPSSliderChange.bind(this));
};
@ -54,8 +45,7 @@
if (!this.framesheet.hasFrameAtIndex(this.animIndex)) {
this.animIndex = 0;
}
this.renderer.render(this.framesheet.getFrameByIndex(this.animIndex), this.previewCanvas, this.dpi);
this.renderer.render(this.framesheet.getFrameByIndex(this.animIndex));
this.animIndex++;
this.startAnimationTimer();
};

View File

@ -3,62 +3,227 @@
ns.DrawingController = function (frame, container, dpi) {
this.dpi = dpi;
// Public
this.frame = frame;
this.overlay = pskl.model.Frame.createEmptyFromFrame(frame);
// TODO(vincz): Store user prefs in a localstorage string ?
var renderingOptions = {
"dpi": dpi,
"hasGrid" : true
};
// Private
/**
* @public
*/
this.frame = frame;
/**
* @public
*/
this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(frame);
/**
* @private
*/
this.container = container;
this.mainCanvas = this.createMainCanvas();
this.overlayCanvas = this.createOverlayCanvas();
this.renderer = new pskl.rendering.FrameRenderer();
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.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) {
this.renderer.updateDPI(newDPI);
this.overlayRenderer.updateDPI(newDPI);
this.renderer.render(this.frame);
this.overlayRenderer.render(this.overlayFrame);
};
ns.DrawingController.prototype.renderFrame = function () {
this.renderer.render(this.frame, this.mainCanvas, this.dpi);
this.renderer.render(this.frame);
};
ns.DrawingController.prototype.renderFramePixel = function (col, row) {
this.renderer.drawPixel(col, row, this.frame, this.mainCanvas, this.dpi);
this.renderer.drawPixel(col, row, this.frame);
};
ns.DrawingController.prototype.renderOverlay = function () {
this.renderer.render(this.overlay, this.overlayCanvas, this.dpi);
this.overlayRenderer.render(this.overlayFrame);
};
ns.DrawingController.prototype.clearOverlay = function () {
this.overlay = pskl.model.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 = "drawing-canvas";
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;
this.overlayFrame = pskl.model.Frame.createEmptyFromFrame(this.frame);
this.overlayRenderer.clear();
};
})();

View File

@ -6,13 +6,17 @@
this.framesheet = framesheet;
this.container = container;
this.renderer = new pskl.rendering.FrameRenderer();
$.subscribe(Events.REDRAW_PREVIEWFILM, $.proxy(function(evt) {
this.createPreviews()
}, this));
};
ns.PreviewFilmController.prototype.init = function() {
var addFrameButton = $('#add-frame-button')[0];
addFrameButton.addEventListener('mousedown', this.addFrame.bind(this));
this.createPreviews();
};
ns.PreviewFilmController.prototype.addFrame = function () {
@ -21,19 +25,133 @@
};
ns.PreviewFilmController.prototype.createPreviews = function () {
this.container.innerHTML = "";
for (var i = 0, l = this.framesheet.getFrameCount(); i < l ; i++) {
this.container.appendChild(this.createPreviewTile(i));
// TODO(vincz): Full redraw on any drawing modification, optimize.
this.container.html("");
var frameCount = this.framesheet.getFrameCount();
for (var i = 0, l = frameCount; i < l ; i++) {
this.container.append(this.createInterstitialTile_(i));
this.container.append(this.createPreviewTile_(i, this.framesheet));
}
this.container.append(this.createInterstitialTile_(frameCount));
var needDragndropBehavior = !!(frameCount > 1);
if(needDragndropBehavior) {
this.initDragndropBehavior_();
}
};
ns.PreviewFilmController.prototype.createPreviewTile = function(tileNumber) {
var frame = this.framesheet.getFrameByIndex(tileNumber);
var width = frame.getWidth() * this.dpi,
height = frame.getHeight() * this.dpi;
/**
* @private
*/
ns.PreviewFilmController.prototype.createInterstitialTile_ = function (tileNumber) {
var initerstitialTile = document.createElement("div");
initerstitialTile.className = "interstitial-tile"
initerstitialTile.setAttribute("data-tile-type", "interstitial");
initerstitialTile.setAttribute("data-inject-drop-tile-at", tileNumber);
return initerstitialTile;
};
/**
* @private
*/
ns.PreviewFilmController.prototype.initDragndropBehavior_ = function () {
var tiles = $(".preview-tile");
// Each preview film tile is draggable.
tiles.draggable( {
//containment: '.left-nav',
stack: '.preview-tile',
cursor: 'move',
revert: true,
start: function(event, ui) {
// We only show the fake interstitial tiles when starting the
// drag n drop interaction. We hide them when the DnD is done.
$('#preview-list').addClass("show-interstitial-tiles");
},
stop: function() {
$('#preview-list').removeClass("show-interstitial-tiles");
}
});
// Each preview film tile is a drop target. This allow us to swap two tiles.
// However, we want to be able to insert a tile between two other tiles.
// For that we created fake interstitial tiles that are used as drop targets as well.
var droppableTiles = $(".interstitial-tile");
$.merge(droppableTiles, tiles);
droppableTiles.droppable( {
accept: ".preview-tile",
tolerance: "pointer",
activeClass: "droppable-active",
hoverClass: "droppable-hover-active",
drop: $.proxy(this.onDrop_, this)
});
};
/**
* @private
*/
ns.PreviewFilmController.prototype.onDrop_ = function( event, ui ) {
var activeFrame;
// When we drag from an element, the drag could start from a nested DOM element
// inside the drag target. We normalize that by taking the correct ancestor:
var originTile = $(event.srcElement).closest(".preview-tile");
var originFrameId = parseInt(originTile.data("tile-number"), 10);
var dropTarget = $(event.target);
if(dropTarget.data("tile-type") == "interstitial") {
var targetInsertionId = parseInt(dropTarget.data("inject-drop-tile-at"), 10);
// In case we drop outside of the tile container
if(isNaN(originFrameId) || isNaN(targetInsertionId)) {
return;
}
//console.log("origin-frame: "+originFrameId+" - targetInsertionId: "+ targetInsertionId)
this.framesheet.moveFrame(originFrameId, targetInsertionId);
activeFrame = targetInsertionId;
// The last fake interstitial tile is outside of the framesheet array bound.
// It allow us to append after the very last element in this fake slot.
// However, when setting back the active frame, we have to make sure the
// frame does exist.
if(activeFrame > (this.framesheet.getFrameCount() - 1)) {
activeFrame = targetInsertionId - 1;
}
}
else {
var targetSwapId = parseInt(dropTarget.data("tile-number"), 10);
// In case we drop outside of the tile container
if(isNaN(originFrameId) || isNaN(targetSwapId)) {
return;
}
//console.log("origin-frame: "+originFrameId+" - targetSwapId: "+ targetSwapId)
this.framesheet.swapFrames(originFrameId, targetSwapId);
activeFrame = targetSwapId;
}
$('#preview-list').removeClass("show-interstitial-tiles");
// TODO(vincz): deprecate.
piskel.setActiveFrameAndRedraw(activeFrame);
// TODO(vincz): move localstorage request to the model layer?
$.publish(Events.LOCALSTORAGE_REQUEST);
};
/**
* @private
* TODO(vincz): clean this giant rendering function & remove listeners.
*/
ns.PreviewFilmController.prototype.createPreviewTile_ = function(tileNumber, framesheet) {
var currentFrame = this.framesheet.getFrameByIndex(tileNumber);
var previewTileRoot = document.createElement("li");
var classname = "preview-tile";
previewTileRoot.setAttribute("data-tile-number", tileNumber);
if (piskel.getActiveFrameIndex() == tileNumber) {
classname += " selected";
@ -42,18 +160,11 @@
var canvasContainer = document.createElement("div");
canvasContainer.className = "canvas-container";
canvasContainer.setAttribute('style', 'width:' + width + 'px; height:' + height + 'px;');
var canvasBackground = document.createElement("div");
canvasBackground.className = "canvas-background";
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) {
// has not class tile-action:
if(!evt.target.classList.contains('tile-action')) {
@ -66,11 +177,19 @@
canvasPreviewDuplicateAction.innerHTML = "dup"
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.dpi);
canvasContainer.appendChild(canvasPreview);
//this.renderer.render(this.framesheet.getFrameByIndex(tileNumber), canvasPreview);
// 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.
var renderingOptions = {"dpi": this.dpi };
var currentFrameRenderer = new pskl.rendering.FrameRenderer($(canvasContainer), renderingOptions, "tile-view");
currentFrameRenderer.init(currentFrame);
previewTileRoot.appendChild(canvasContainer);
previewTileRoot.appendChild(canvasPreviewDuplicateAction);
@ -79,7 +198,9 @@
canvasPreviewDeleteAction.className = "tile-action"
canvasPreviewDeleteAction.innerHTML = "del"
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);
}

56
js/drawingtools/Move.js Normal file
View File

@ -0,0 +1,56 @@
/*
* @provide pskl.drawingtools.Move
*
* @require pskl.utils
*/
(function() {
var ns = $.namespace("pskl.drawingtools");
ns.Move = function() {
this.toolId = "tool-move"
// Stroke's first point coordinates (set in applyToolAt)
this.startCol = null;
this.startRow = null;
};
pskl.utils.inherit(ns.Move, ns.BaseTool);
/**
* @override
*/
ns.Move.prototype.applyToolAt = function(col, row, color, drawer) {
this.startCol = col;
this.startRow = row;
this.frameClone = drawer.frame.clone();
};
ns.Move.prototype.moveToolAt = function(col, row, color, drawer) {
var colDiff = col - this.startCol, rowDiff = row - this.startRow;
if (colDiff != 0 || rowDiff != 0) {
this.shiftFrame(colDiff, rowDiff, drawer.frame, this.frameClone);
drawer.renderFrame();
}
};
ns.Move.prototype.shiftFrame = function (colDiff, rowDiff, frame, reference) {
var color;
for (var col = 0 ; col < frame.getWidth() ; col++) {
for (var row = 0 ; row < frame.getHeight() ; row++) {
if (reference.containsPixel(col - colDiff, row - rowDiff)) {
color = reference.getPixel(col - colDiff, row - rowDiff);
} else {
color = Constants.TRANSPARENT_COLOR;
}
frame.setPixel(col, row, color)
}
}
};
/**
* @override
*/
ns.Move.prototype.releaseToolAt = function(col, row, color, drawer) {
this.moveToolAt(col, row, color, drawer);
};
})();

View File

@ -24,7 +24,7 @@
this.startRow = row;
// Drawing the first point of the rectangle in the fake overlay canvas:
drawer.overlay.setPixel(col, row, color);
drawer.overlayFrame.setPixel(col, row, color);
drawer.renderOverlay();
};
@ -42,7 +42,7 @@
if(color == Constants.TRANSPARENT_COLOR) {
color = Constants.SELECTION_TRANSPARENT_COLOR;
}
drawer.overlay.setPixel(strokePoints[i].col, strokePoints[i].row, color);
drawer.overlayFrame.setPixel(strokePoints[i].col, strokePoints[i].row, color);
}
drawer.renderOverlay();
};

View File

@ -34,18 +34,16 @@
// The fake canvas where we will draw the preview of the stroke:
// Drawing the first point of the stroke in the fake overlay canvas:
drawer.updateOverlay(col, row, color);
drawer.overlayFrame.setPixel(col, row, color);
drawer.renderOverlay();
};
ns.Stroke.prototype.moveToolAt = function(col, row, color, drawer) {
drawer.clearOverlay();
// 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.getLinePixels_(this.startCol, col, this.startRow, row);
// Clean overlay canvas:
this.canvasOverlay.getContext("2d").clearRect(
0, 0, this.canvasOverlay.width, this.canvasOverlay.height);
// Drawing current stroke:
for(var i = 0; i< strokePoints.length; i++) {
@ -59,8 +57,9 @@
// eg deleting the equivalent of a stroke.
color = Constants.SELECTION_TRANSPARENT_COLOR;
}
drawer.updateOverlay(strokePoints[i].col, strokePoints[i].row, color);
drawer.overlayFrame.setPixel(strokePoints[i].col, strokePoints[i].row, color);
}
drawer.renderOverlay();
};
/**
@ -75,7 +74,7 @@
var strokePoints = this.getLinePixels_(this.startCol, col, this.startRow, row);
for(var i = 0; i< strokePoints.length; i++) {
// Change model:
drawer.updateFrame(strokePoints[i].col, strokePoints[i].row, color);
drawer.frame.setPixel(strokePoints[i].col, strokePoints[i].row, color);
}
// Draw in canvas:
// TODO: Remove that when we have the centralized redraw loop

3017
js/lib/jquery-ui-1.8.23.custom.js vendored Executable file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
jquery-ui-1.8.23.custom.js was generated at: http://http://jqueryui.com/download
and contains:
jQuery ui core:
core
widget
position
mouse
Interactions:
Draggable
Droppable
Resizable

View File

@ -1,58 +1,102 @@
(function () {
var ns = $.namespace("pskl.model");
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.serialize = function () {
return JSON.stringify(this.pixels);
};
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.containsPixel = function (col, row) {
return col >= 0 && row >= 0 && col <= this.pixels.length && row <= this.pixels[0].length;
};
(function () {
var ns = $.namespace("pskl.model");
ns.Frame = function (pixels) {
this.pixels = this.clonePixels_(pixels);
this.previousStates = [this.getPixels()];
this.stateIndex = 0;
};
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 () {
return new ns.Frame(this.getPixels());
};
/**
* Returns a copy of the pixels used by the frame
*/
ns.Frame.prototype.getPixels = function () {
return this.clonePixels_(this.pixels)
};
/**
* Copies the passed pixels into the frame.
*/
ns.Frame.prototype.setPixels = function (pixels) {
this.pixels = this.clonePixels_(pixels);
};
/**
* Clone a set of pixels. Should be static utility method
* @private
*/
ns.Frame.prototype.clonePixels_ = function (pixels) {
var clonedPixels = [];
for (var col = 0 ; col < pixels.length ; col++) {
clonedPixels[col] = pixels[col].slice(0 , pixels[col].length);
}
return clonedPixels;
};
ns.Frame.prototype.serialize = function () {
return JSON.stringify(this.pixels);
};
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.containsPixel = function (col, row) {
return col >= 0 && row >= 0 && col < this.pixels.length && row < this.pixels[0].length;
};
ns.Frame.prototype.saveState = function () {
// remove all states past current state
this.previousStates.length = this.stateIndex + 1;
// push new state
this.previousStates.push(this.getPixels());
// set the stateIndex to latest saved state
this.stateIndex = this.previousStates.length - 1;
};
ns.Frame.prototype.loadPreviousState = function () {
if (this.stateIndex > 0) {
this.stateIndex--;
this.setPixels(this.previousStates[this.stateIndex]);
}
};
ns.Frame.prototype.loadNextState = function () {
if (this.stateIndex < this.previousStates.length - 1) {
this.stateIndex++;
this.setPixels(this.previousStates[this.stateIndex]);
}
};
})();

View File

@ -1,6 +1,8 @@
(function () {
var ns = $.namespace("pskl.model");
ns.FrameSheet = function () {
ns.FrameSheet = function (width, height) {
this.width = width;
this.height = height;
this.frames = [];
};
@ -9,7 +11,7 @@
};
ns.FrameSheet.prototype.addEmptyFrame = function () {
this.addFrame(ns.Frame.createEmpty(width, height));
this.addFrame(ns.Frame.createEmpty(this.width, this.height));
};
ns.FrameSheet.prototype.addFrame = function (frame) {
@ -93,4 +95,29 @@
var frame = this.getFrameByIndex(index);
this.frames.splice(index + 1, 0, frame.clone());
};
ns.FrameSheet.prototype.moveFrame = function(originIndex, destinationIndex) {
var frameToMove = this.getFrameByIndex(originIndex);
this.frames.splice(destinationIndex, 0,frameToMove);
if(destinationIndex <= originIndex) {
originIndex++;
}
this.removeFrameByIndex(originIndex);
};
ns.FrameSheet.prototype.swapFrames = function(indexFrame1, indexFrame2) {
if(isNaN(indexFrame1) || isNaN(indexFrame1) ||
(!this.hasFrameAtIndex(indexFrame1) && !this.hasFrameAtIndex(indexFrame2))) {
throw "Bad indexes for swapFrames Framesheet function.";
}
if(indexFrame1 == indexFrame2) {
return;
}
else {
var swapFrame = this.frames[indexFrame1];
this.frames[indexFrame1] = this.frames[indexFrame2];
this.frames[indexFrame2] = swapFrame;
}
};
})();

View File

@ -11,38 +11,21 @@ $.namespace("pskl");
*/
var frameSheet,
// Temporary zoom implementation to easily get bigger canvases to
// see how good perform critical algorithms on big canvas.
zoom = 1,
// Configuration:
// Canvas size in pixel size (not dpi related)
framePixelWidth = 32 * zoom,
framePixelHeight = 32 * zoom,
framePixelWidth = 32,
framePixelHeight = 32,
// Scaling factors for a given frameSheet rendering:
// Main drawing area:
drawingCanvasDpi = Math.ceil(20/ zoom),
// Canvas previous in the slideshow:
previewTileCanvasDpi = Math.ceil(4 / zoom),
// Ainmated canvas preview:
previewAnimationCanvasDpi = Math.ceil(8 / zoom),
drawingCanvasDpi = 20,
// Canvas preview film canvases:
previewTileCanvasDpi = 4,
// Animated canvas preview:
previewAnimationCanvasDpi = 8,
// DOM references:
drawingAreaContainer,
drawingAreaCanvas,
previewCanvas,
// States:
isClicked = false,
isRightClicked = false,
activeFrameIndex = -1,
animIndex = 0,
penColor = Constants.DEFAULT_PEN_COLOR,
activeFrameIndex = -1,
currentFrame = null;
currentToolBehavior = null,
previousMousemoveTime = 0;
/**
* Main application controller
@ -50,14 +33,15 @@ $.namespace("pskl");
var piskel = {
init : function () {
var emptyFrame = pskl.model.Frame.createEmpty(framePixelWidth, framePixelHeight);
frameSheet = new pskl.model.FrameSheet();
frameSheet.addFrame(emptyFrame);
piskel.initDPIs_();
frameSheet = new pskl.model.FrameSheet(framePixelWidth, framePixelHeight);
frameSheet.addEmptyFrame();
this.drawingController = new pskl.controller.DrawingController(
emptyFrame,
$('#drawing-canvas-container')[0],
frameSheet.getFrameByIndex(0),
$('#drawing-canvas-container'),
drawingCanvasDpi
);
@ -65,20 +49,21 @@ $.namespace("pskl");
this.animationController = new pskl.controller.AnimatedPreviewController(
frameSheet,
$('#preview-canvas-container')[0],
$('#preview-canvas-container'),
previewAnimationCanvasDpi
);
this.previewsController = new pskl.controller.PreviewFilmController(
frameSheet,
$('#preview-list')[0],
$('#preview-list'),
previewTileCanvasDpi
);
this.animationController.init();
this.previewsController.init();
pskl.HistoryManager.init();
pskl.NotificationService.init();
pskl.LocalStorageService.init(frameSheet);
@ -91,27 +76,71 @@ $.namespace("pskl");
this.finishInit();
pskl.LocalStorageService.displayRestoreNotification();
}
$.subscribe('SET_ACTIVE_FRAME', function(evt, frameId) {
piskel.setActiveFrameAndRedraw(frameId);
});
$.subscribe('FRAMESHEET_RESET', function(evt, frameId) {
piskel.redraw();
});
},
/**
* Override default DPIs.
* @private
*/
initDPIs_ : function() {
drawingCanvasDpi = piskel.calculateDPIsForDrawingCanvas_();
// TODO(vincz): Add throttling on window.resize event.
$(window).resize($.proxy(function() {
drawingCanvasDpi = piskel.calculateDPIsForDrawingCanvas_();
this.drawingController.updateDPI(drawingCanvasDpi);
}, this));
// TODO(vincz): Check for user settings eventually from localstorage.
},
/**
* @private
*/
calculateDPIsForDrawingCanvas_ : function() {
var availableViewportHeight = $('.main-panel').height() - 50,
availableViewportWidth = $('.main-panel').width(),
previewHeight = $(".preview-container").height(),
previewWidth = $(".preview-container").width();
var heightBoundDpi = Math.floor(availableViewportHeight / framePixelHeight),
widthBoundDpi = Math.floor(availableViewportWidth / framePixelWidth);
var dpi = Math.min(heightBoundDpi, widthBoundDpi);
var drawingCanvasHeight = dpi * framePixelHeight;
var drawingCanvasWidth = dpi * framePixelWidth;
// Check if preview and drawing canvas overlap
var heightGap = drawingCanvasHeight + previewHeight - availableViewportHeight,
widthGap = drawingCanvasWidth + previewWidth - availableViewportWidth;
if (heightGap > 0 && widthGap > 0) {
// Calculate the DPI change needed to bridge height and width gap
var heightGapDpi = Math.ceil(heightGap / framePixelHeight),
widthGapDpi = Math.ceil(widthGap / framePixelWidth);
// substract smallest dpi change to initial dpi
dpi -= Math.min(heightGapDpi, widthGapDpi);
}
return dpi;
},
finishInit : function () {
$.subscribe(Events.TOOL_SELECTED, function(evt, toolBehavior) {
console.log("Tool selected: ", toolBehavior);
currentToolBehavior = toolBehavior;
});
$.subscribe(Events.COLOR_SELECTED, function(evt, color) {
console.log("Color selected: ", color);
penColor = color;
});
$.subscribe(Events.REFRESH, function() {
piskel.setActiveFrameAndRedraw(0);
});
// TODO: Move this into their service or behavior files:
this.initDrawingArea();
pskl.ToolSelector.init();
pskl.Palette.init(frameSheet);
},
@ -149,7 +178,7 @@ $.namespace("pskl");
setActiveFrame: function(index) {
activeFrameIndex = index;
this.drawingController.frame = frameSheet.getFrameByIndex(index);
this.drawingController.frame = this.getCurrentFrame();
},
setActiveFrameAndRedraw: function(index) {
@ -171,112 +200,8 @@ $.namespace("pskl");
return 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));
drawingAreaContainer.style.width = framePixelWidth * drawingCanvasDpi + "px";
drawingAreaContainer.style.height = framePixelHeight * drawingCanvasDpi + "px";
drawingAreaContainer.addEventListener('contextmenu', this.onCanvasContextMenu);
},
removeFrame: function(frameIndex) {
frameSheet.removeFrameByIndex(frameIndex);
this.setActiveFrameAndRedraw(frameIndex - 1);
},
duplicateFrame: function(frameIndex) {
frameSheet.duplicateFrameByIndex(frameIndex);
this.setActiveFrameAndRedraw(frameIndex + 1);
},
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,
penColor,
this.drawingController
);
$.publish(Events.LOCALSTORAGE_REQUEST);
},
onMousemove : function (event) {
var currentTime = new Date().getTime();
// Throttling of the mousemove event:
if ((currentTime - previousMousemoveTime) > 40 ) {
if (isClicked) {
var spriteCoordinate = this.getSpriteCoordinate(event);
currentToolBehavior.moveToolAt(
spriteCoordinate.col,
spriteCoordinate.row,
penColor,
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);
}
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.
// TODO: Remove that when we have the centralized redraw loop
this.previewsController.createPreviews();
}
if(isRightClicked) {
$.publish(Events.CANVAS_RIGHT_CLICK_RELEASED);
}
isClicked = false;
isRightClicked = false;
var spriteCoordinate = this.getSpriteCoordinate(event);
currentToolBehavior.releaseToolAt(
spriteCoordinate.col,
spriteCoordinate.row,
penColor,
this.drawer
);
},
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
}
getCurrentFrame : function () {
return frameSheet.getFrameByIndex(activeFrameIndex);
},
// TODO(julz): Create package ?

View File

@ -1,20 +1,77 @@
(function () {
var ns = $.namespace("pskl.rendering");
ns.FrameRenderer = function () {};
ns.FrameRenderer.prototype.render = function (frame, canvas, dpi) {
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, canvas, dpi);
}
ns.FrameRenderer = function (container, renderingOptions, className) {
this.defaultRenderingOptions = {
"hasGrid" : false
};
renderingOptions = $.extend(true, {}, this.defaultRenderingOptions, renderingOptions);
if(container == undefined) {
throw "Bad FrameRenderer initialization. <container> undefined.";
}
if(isNaN(renderingOptions.dpi)) {
throw "Bad FrameRenderer initialization. <dpi> not well defined.";
}
this.container = container;
this.dpi = renderingOptions.dpi;
this.className = className;
this.canvas = null;
this.hasGrid = renderingOptions.hasGrid;
this.gridStrokeWidth = 0;
this.lastRenderedFrame = null;
// Flag to know if the config was altered
this.canvasConfigDirty = true;
if(this.hasGrid) {
$.subscribe(Events.GRID_DISPLAY_STATE_CHANGED, $.proxy(this.showGrid, this));
}
};
ns.FrameRenderer.prototype.init = function (frame) {
this.render(frame);
this.lastRenderedFrame = frame;
};
ns.FrameRenderer.prototype.updateDPI = function (newDPI) {
this.dpi = newDPI;
this.canvasConfigDirty = true;
};
ns.FrameRenderer.prototype.showGrid = function (evt, show) {
this.gridStrokeWidth = 0;
if(show) {
this.gridStrokeWidth = Constants.GRID_STROKE_WIDTH;
}
this.canvasConfigDirty = true;
if(this.lastRenderedFrame) {
this.render(this.lastRenderedFrame);
}
};
ns.FrameRenderer.prototype.drawPixel = function (col, row, frame, canvas, dpi) {
var context = canvas.getContext('2d');
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) {
var context = this.getCanvas_(frame, col, row).getContext('2d');
var color = frame.getPixel(col, row);
if(color == Constants.TRANSPARENT_COLOR) {
context.clearRect(col * dpi, row * dpi, dpi, dpi);
context.clearRect(this.getFrameY_(col), this.getFrameY_(row), this.dpi, this.dpi);
}
else {
if(color != Constants.SELECTION_TRANSPARENT_COLOR) {
@ -22,7 +79,94 @@
$.publish(Events.COLOR_USED, [color]);
}
context.fillStyle = color;
context.fillRect(col * dpi, row * dpi, dpi, dpi);
context.fillRect(this.getFrameY_(col), this.getFrameY_(row), this.dpi, this.dpi);
}
this.lastRenderedFrame = frame;
};
ns.FrameRenderer.prototype.clear = function (col, row, frame) {
var canvas = this.getCanvas_(frame, col, row)
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
*/
ns.FrameRenderer.prototype.getCanvas_ = function (frame) {
if(this.canvasConfigDirty) {
$(this.canvas).remove();
var col = frame.getWidth(),
row = frame.getHeight();
var canvas = document.createElement("canvas");
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";
if(this.className) {
canvasClassname += " " + this.className;
}
canvas.setAttribute("class", canvasClassname);
this.container.append(canvas);
if(this.gridStrokeWidth > 0) {
this.drawGrid_(canvas, pixelWidth, pixelHeight, col, row);
}
this.canvas = canvas;
this.canvasConfigDirty = false;
}
return this.canvas;
};
})();