forked from dnieh/pixel-grid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpixelGrid.js
More file actions
311 lines (264 loc) · 8.8 KB
/
pixelGrid.js
File metadata and controls
311 lines (264 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
'use strict';
var pixelGrid = (function($) {
var PIXEL_SCALE = 10; // Default: 10 literal pixel is 1 grid display pixel
var $canvas = $('[data-anchor="grid"]');
var canvas = $canvas[0];
var currentColor = '#000'; // default black
var backgroundColor = '#f2f2f2';
var width;
var height;
var c; // context
var cachedImage;
var ctx = canvas.getContext('2d');
var drawing = false;
var isFill = false;
function setInitialWidthAndHeight(initialWidth, initialHeight) {
width = initialWidth ||
$canvas.closest('[data-section="canvas"]').outerWidth() - 30; // -30 bootstrap padding
height = initialHeight || calculateHeight();
setDimensions(width, height);
}
/**
* Tries to calculate height based on elements with the data-add-height attribute.
* If data attribute not available, automatically sets height to width.
*/
function calculateHeight() {
var $sectionsHeight = $('[data-add-height]');
var tempHeight = 0;
if (!$sectionsHeight) {
tempHeight = width;
} else {
$sectionsHeight.each(function() {
tempHeight += $(this).outerHeight();
});
tempHeight = ($(window).height() - tempHeight) / 2;
}
// return tempHeight;
return $('[data-section="settings"]').height();
}
function setDimensions(widthInput, heightInput) {
// Save a copy of the current image
var dataURL = $canvas[0].toDataURL();
var image = new Image();
image.src = dataURL;
cachedImage = image;
if (widthInput !== -1) {
$canvas.attr('width', widthInput);
width = widthInput;
}
if (heightInput !== -1) {
$canvas.attr('height', heightInput);
height = heightInput;
}
}
/**
* Listen for triggers from width and height input fields
*/
function gridDimensionsListener() {
$canvas.on('gridSetWidth', function(event, newWidth) {
newWidth *= PIXEL_SCALE;
setDimensions(newWidth, -1);
draw(newWidth, height, true);
});
$canvas.on('gridSetHeight', function(event, newHeight) {
newHeight *= PIXEL_SCALE;
setDimensions(-1, newHeight);
draw(width, newHeight, true);
});
}
function clickEventListener() {
var draw = function(e) {
var x;
var y;
var startX;
var startY;
// Get the relative position (offset)
x = e.offsetX; // column or x-axis
y = e.offsetY; // row or y-axis
// Determine which pixel representation we're on. For example,
// if the (x, y) coordinates are (8, 8), then we want to color
// in the square starting from (1, 1) through (9, 9) while leaving
// the border the existing grid colors of grey and red.
startX = Math.floor(x / 10) * 10 + 1;
startY = Math.floor(y / 10) * 10 + 1;
// Fill the square with the selected color
c.fillStyle = currentColor;
c.fillRect(startX, startY, 9, 9);
// Update the live render and the css code output
x = getScaledCoordinate(startX);
y = getScaledCoordinate(startY);
$canvas.trigger('gridPixelAdded', [x, y, currentColor]);
};
$canvas.on('mousedown', function(e) {
draw(e);
drawing = true;
});
$canvas.on('mouseup', function(e) {
drawing = false;
});
$canvas.on('mousemove', function(e) {
if (drawing) {
draw(e);
}
});
}
function getScaledCoordinate(coordinate) {
return (coordinate - 1) / 10;
}
function setCurrentColor() {
$canvas.on('gridSetCurrentColor', function(event, color) {
currentColor = color;
});
}
/**
* @param gWidth {number} grid width
* @param gHeight {number} grid height
* @param preserveCurrentImage {bool}
*/
function draw(gWidth, gHeight, preserveCurrentImage) {
preserveCurrentImage = preserveCurrentImage || false;
// Light grey background
c.fillStyle = backgroundColor;
c.fillRect(0, 0, gWidth, gHeight);
// Grey grid
c.fillStyle = "#999"
for (var i = 0; i < gWidth || i < gHeight; i += 10) {
c.fillRect(i, 0, 1, gHeight);
c.fillRect(0, i, gWidth, 1);
}
// Red overlay grid
c.fillStyle = "#d9534f";
for (var i = 0; i < gWidth || i < gHeight; i+= 100) {
c.fillRect(i, 0, 1, gHeight);
c.fillRect(0, i, gWidth, 1);
}
// Re-draw cached image if it exists
if (cachedImage && preserveCurrentImage) {
c.drawImage(cachedImage, 0, 0);
}
}
function clearGridListener() {
$('[data-anchor="clearButton"]').on('click', function() {
clear();
});
}
function validateDimensionInput(side) {
if (isNaN(side)) {
return false;
} else if (side < 0 || side > 10000) {
return false;
} else {
return true;
}
}
function getPixel(x, y)
{
var p = ctx.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
return hex;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
function create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
//==========================================================================
// PUBLIC API
//==========================================================================
var init = function(initialWidth, initialHeight) {
setInitialWidthAndHeight(initialWidth, initialHeight);
gridDimensionsListener();
clickEventListener();
setCurrentColor();
clearGridListener();
if (canvas.getContext) {
c = canvas.getContext('2d');
draw(width, height);
// Let width and height input know we're initialized to dynamically
// set their values
$canvas.trigger('gridDimensionsInitialized', [width, height]);
} else {
console.error('Error: Could not get canvas context.');
return;
}
};
var clear = function() {
c.clearRect(0, 0, width, height);
draw(width, height, false); // redraws the grid without the cached image
$canvas.trigger('gridCleared');
};
/**
* @param widthInput {number}
*/
var width = function(widthInput) {
if (!widthInput || !validateDimensionInput(widthInput)) {
console.error('Error: please specify a valid width.');
return;
}
setDimensions(widthInput, -1);
draw(widthInput, height, true);
};
/**
* @param heightInput {number}
*/
var height = function(heightInput) {
if (!heightInput || !validateDimensionInput(heightInput)) {
console.error('Error: please specify a valid height.');
return;
}
setDimensions(-1, heightInput);
draw(width, heightInput, true);
};
/**
* Public API Method for single pixel
* TODO -- validate params
*/
var colorPixel = function(x, y, color) {
var startX = x * 10 + 1;
var startY = y * 10 + 1;
c.fillStyle = color;
c.fillRect(startX, startY, 9, 9);
startX = getScaledCoordinate(startX);
startY = getScaledCoordinate(startY);
$canvas.trigger('gridPixelAdded', [startX, startY, color]);
};
/**
* Public API for JSON list of pixels
* TODO -- validate params, JSON, and show error message
*/
var batchColor = function(list) {
var details = list.coordinates;
for (var i in details) {
colorPixel(details[i].x, details[i].y, details[i].color);
}
};
var scan = function () {
var arr = create2DArray((canvas.height/10) + 1);
for (var i=0; i< canvas.width; i=i+10) {
for (var j=0; j< canvas.height; j=j+10) {
arr[j/10][i/10] = getPixel(i+1, j+1);
}
}
return arr;
};
return {
init: init,
clear: clear,
width: width,
height: height,
colorPixel: colorPixel,
batchColor: batchColor,
scan: scan
};
}($));
// Wait for page to load, otherwise grid could initialized before pixelArtCreator.js
$(function() {
pixelGrid.init();
});