Algorithm for adding black bars to an image - javascript

I am trying to write a function that adds black bars to an image such as in the example below:
before and after
I have the following code. I believe the algorithm is correct, however, it only works for certain images and certain values. For example, it does work when the "cuts" variable is equal to 7 and the resolution of the uploaded image is 1920x1080, however it doesn't for any other values other than 7, 1 or 2. Why?
Also, if you think of a better algorithm please share it with me.
rectangleButton.addEventListener("click", () => {
if(loadCounter === 4) {
var cuts = parseInt(text.value);
text.value = null;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var divisions = (2*cuts)+1;
var lines = canvas.height;
var columns = canvas.width;
console.log(canvas.height);
console.log(canvas.width);
console.log(divisions);
var k = 1;
var scannedRectangleImage = ctx.getImageData(0, 0, canvas.width, canvas.height);
var scannedRectangleImageData = scannedRectangleImage.data;
for(k = 1; k < 2*cuts; k = k+2) {
for(var i = k*lines/divisions; i < (k+1)*lines/divisions; i++)
{
for(var j = 0; j < columns; j++)
{
scannedRectangleImageData[i*4*columns+4*j] = 0;
scannedRectangleImageData[i*4*columns+4*j+1] = 0;
scannedRectangleImageData[i*4*columns+4*j+2] = 0;
}
}
console.log(k + " < " + 2*cuts);
}
scannedRectangleImage.data = scannedRectangleImageData;
ctx.putImageData(scannedRectangleImage, 0, 0); }
else
{
alert("Image upload is not ready");
}
})

This is how I would do it
function drawImage(image) {
const canvas = document.getElementById('canvas');
canvas.setAttribute('width', image.width);
canvas.setAttribute('height', image.height);
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);
const stripeCount = document.getElementById('stripeCount').value;
const sectionCount = 2 * stripeCount + 1;
const stripeHeight = Math.ceil(image.height / sectionCount);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (let i = 0; i < stripeCount; i++) {
drawStripe(2 * i + 1, stripeHeight, imageData.data, canvas.width);
}
ctx.putImageData(imageData, 0, 0);
}
function drawStripe(stripeIdx, stripeHeight, imageData, imageWidth) {
const lineStart = stripeIdx * stripeHeight;
const dataStart = lineStart * imageWidth * 4;
const dataLength = stripeHeight * imageWidth * 4;
for (let idx = dataStart, l = dataStart + dataLength; idx < l; idx += 4) {
imageData[idx] = 0;
imageData[idx + 1] = 0;
imageData[idx + 2] = 0;
}
}

Related

How do i get image data from external url - and return colors

Im using clusterfck.js to analyze and return colors. I wan't to grap images from search-results, but it seems to be a problem with the way clusterfck does the data reading. Here's the code from clusterfck:
$(".kmeans-button").click(function() {
if (!colors) {
colors = getImageColors();
}
var k = $(this).attr("data-k"); // $.data() returned undefined
$("#clusters").empty().append("<div>calculating distances...</div>");
kmeans.clusterColors(colors, k); // Threaded analyzing (worker)
})
function getImageColors() {
var img = $("#test-image");
var width = img.width();
var height = img.height();
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(img.get(0), 0, 0);
var data = context.getImageData(0, 0, width, height).data;
var colors = [];
for(var x = 0; x < width-12; x += 3) {
for(var y = 0; y < height-12; y += 3) { // sample image, every 3rd row and column
var offs = x*4 + y*4*width;
var color = [data[offs + 0], data[offs + 1], data[offs + 2]];
colors.push(color);
}
}
return colors;
}
I tried to put in img.crossOrigin = "Anonymous"; with no luck. I guess it needs to be loaded in af function and somehow callback colors. This is the best i could come up with, but it's not working.
$(".kmeans-button").click(function() {
if (!colors) {
getImageColors2(function(colors2) {
colors=colors2.slice(0);
var k = $(this).attr("data-k-e"); // $.data() returned undefined
$("#clusters").empty().append("<div>calculating colors...</div>");
kmeans.clusterColors(colors, k);
})
}
})
function getImageColors2(callback) {
var img2= document.getElementById("test-image");
var img = new Image();
img.onload = function () {
var width = img.width();
var height = img.height();
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(img.get(0), 0, 0);
var data = context.getImageData(0, 0, width, height).data;
var colors = [];
for(var x = 0; x < width-12; x += 3) {
for(var y = 0; y < height-12; y += 3) { // sample image, every 3rd row and column
var offs = x*4 + y*4*width;
var color = [data[offs + 0], data[offs + 1], data[offs + 2]];
colors.push(color);
}
}
callback(colors);
}
img.src=img2.src;
}
I assume that it can't access the data without loading into a image when on a external server. What am i missing her ? Maybe i got it all wrong ?
Thanks for your comments! I got it working now with the callback function :-)
function getpalette(colors) {
$("#clusters").empty().append("<div>calculating colors...</div>");
kmeans_paint.clusterColors(colors, k);
}
$(".kmeans-error-button").click(function() {
k = $(this).attr("data-k-e");
if (!colors) {
getImageColors(getpalette);
}
})
function getImageColors(callback) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var width = img.width;
var height = img.height;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0);
var data = context.getImageData(0, 0, width, height).data;
var colors = [];
for(var x = 0; x < width-12; x += 3) {
for(var y = 0; y < height-12; y += 3) { // sample image, every 3rd row and column
var offs = x*4 + y*4*width;
var color = [data[offs + 0], data[offs + 1], data[offs + 2]];
colors.push(color);
}
}
callback(colors);
}
img.src=document.getElementById("test-image").src;
}

createPattern on canvas issue

As on the attached fiddle, the background image on the canvas is just coming and getting disappearing
I tried both createPattern and drawImage both are having same issue.
I am not an expert in Canvas. Any help would be appreciated
(function(){
var canvas = document.getElementById('c'),
/** #type {CanvasRenderingContext2D} */
ctx = canvas.getContext('2d'),
width = 400,
height = 400,
half_width = width >> 1,
half_height = height >> 1,
size = width * (height + 2) * 2,
delay = 30,
oldind = width,
newind = width * (height + 3),
riprad = 3,
ripplemap = [],
last_map = [],
ripple,
texture,
line_width = 20,
step = line_width * 2,
count = height / line_width;
canvas.width = width;
canvas.height = height;
/*
* Water ripple demo can work with any bitmap image
*/
var imageObj = new Image();
imageObj.onload = function() {
var pattern = ctx.createPattern(imageObj, 'repeat');
ctx.rect(0, 0, width, height);
ctx.fillStyle = pattern;
ctx.fill();
ctx.save();
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/wood-pattern.png';
with (ctx) {
fillStyle = '#ccc';
fillRect(0, 0, width, height);
fillStyle = '#999999';
save();
rotate(-0.785);
for (var i = 0; i < count; i++) {
fillRect(-width, i * step, width * 3, line_width);
}
}
texture = ctx.getImageData(0, 0, width, height);
ripple = ctx.getImageData(0, 0, width, height);
for (var i = 0; i < size; i++) {
last_map[i] = ripplemap[i] = 0;
}
/**
* Main loop
*/
function run() {
newframe();
ctx.putImageData(ripple, 0, 0);
}
/**
* Disturb water at specified point
*/
function disturb(dx, dy) {
dx <<= 0;
dy <<= 0;
for (var j = dy - riprad; j < dy + riprad; j++) {
for (var k = dx - riprad; k < dx + riprad; k++) {
ripplemap[oldind + (j * width) + k] += 128;
}
}
}
/**
* Generates new ripples
*/
function newframe() {
var a, b, data, cur_pixel, new_pixel, old_data;
var t = oldind; oldind = newind; newind = t;
var i = 0;
// create local copies of variables to decrease
// scope lookup time in Firefox
var _width = width,
_height = height,
_ripplemap = ripplemap,
_last_map = last_map,
_rd = ripple.data,
_td = texture.data,
_half_width = half_width,
_half_height = half_height;
for (var y = 0; y < _height; y++) {
for (var x = 0; x < _width; x++) {
var _newind = newind + i, _mapind = oldind + i;
data = (
_ripplemap[_mapind - _width] +
_ripplemap[_mapind + _width] +
_ripplemap[_mapind - 1] +
_ripplemap[_mapind + 1]) >> 1;
data -= _ripplemap[_newind];
data -= data >> 5;
_ripplemap[_newind] = data;
//where data=0 then still, where data>0 then wave
data = 1024 - data;
old_data = _last_map[i];
_last_map[i] = data;
if (old_data != data) {
//offsets
a = (((x - _half_width) * data / 1024) << 0) + _half_width;
b = (((y - _half_height) * data / 1024) << 0) + _half_height;
//bounds check
if (a >= _width) a = _width - 1;
if (a < 0) a = 0;
if (b >= _height) b = _height - 1;
if (b < 0) b = 0;
new_pixel = (a + (b * _width)) * 4;
cur_pixel = i * 4;
_rd[cur_pixel] = _td[new_pixel];
_rd[cur_pixel + 1] = _td[new_pixel + 1];
_rd[cur_pixel + 2] = _td[new_pixel + 2];
}
++i;
}
}
}
canvas.onmousemove = function(/* Event */ evt) {
disturb(evt.offsetX || evt.layerX, evt.offsetY || evt.layerY);
};
setInterval(run, delay);
// generate random ripples
var rnd = Math.random;
var timeOut;
var intrvl = setInterval(function() {
clearTimeout(timeOut);
disturb(0, (height/40));
disturb((width/2.67), (height/40));
disturb((width/1.33), (height/40));
disturb(0, (height/2.67));
disturb((width/2.67), (height/2.67));
disturb((width/1.33), (height/2.67));
disturb(0, (height/1.33));
disturb((width/2.67), (height/1.33));
disturb((width/1.33), (height/1.33));
timeOut= setTimeout(function(){
disturb((width/1.8), (height/8));
disturb((width/-1.2), (height/8));
disturb((width/1.14), (height/8));
disturb((width/1.8), (height/2.13));
disturb((width/-1.2), (height/2.13));
disturb((width/1.14), (height/2.13));
disturb((width/1.8), (height/1.03));
disturb((width/-1.2), (height/1.03));
disturb((width/1.14), (height/1.03));;
},300);
}, 700);
setTimeout(function(){
clearInterval(intrvl);
},3000);
})();
this is the link to the fiddle

Creating/Drawing multiple images on canvas html5

I was wondering what I was doing wrong because I'm making a memory game but the images wouldn't draw on my canvas.
var ctx;
var cardBacks = "Resources/monster.png"; //shows back of card when turned over
var faces = [];
var tiles = [];
var Tile;
var columns = 5;
var rows = 4;
function createTile(x,y){
this.x = x;
this.y = y;
this.width = 70;
ctx.drawImage(cardBacks, this.x, this.y, this.width, this.width);
}
function initialize(){
ctx = document.getElementById("myCanvas").getContext("2d");
for (var i = 0; i < columns; i++) {
for (var j = 0; j < rows; j++) {
tiles.push(createTile(i * 78 + 10, j * 78 + 40));
}
}
}
Try this code with onload callback function.
var ctx;
var cardBacks = new Image();
cardBacks.src = "Resources/monster.png"; //shows back of card when turned over
cardBacks.onload = function() {
ctx.drawImage(cardBacks, this.x, this.y, this.width, this.width);
}
var faces = [];
var tiles = [];
var Tile;
var columns = 5;
var rows = 4;
function createTile(x, y) {
this.x = x;
this.y = y;
this.width = 70;
}
function initialize() {
ctx = document.getElementById("myCanvas").getContext("2d");
for (var i = 0; i < columns; i++) {
for (var j = 0; j < rows; j++) {
tiles.push(createTile(i * 78 + 10, j * 78 + 40));
}
}
}
You need to draw an HTML image element onto the canvas, not a url. I think you could do
var cardBacks = new Image();
cardBacks.src = "Resources/monster.png";
Here's an example: https://jsfiddle.net/yarhqskx/
Here's with multiple (added onload): https://jsfiddle.net/yarhqskx/7/

How to write a convolution filter for Edge detection in FabricJS

I want to write a convolution filter for edge detection in Fabricjs , but the matrix doesn't work.
Here's the Matrix (Idea taken from http://homepages.inf.ed.ac.uk/rbf/HIPR2/sobel.htm):
new fabric.Image.filters.Convolute({ // edge detect
matrix: [[ -1, 0, 1,
-2, 0, 2,
-1, 0, 1 ],
[1, 2, 1,
0 ,0 ,0,
-1, -2, 1 ]]
})
heres the Fiddle
NOTE:- You need to click on the image to get the check boxes for image processing.
Since a native html5 canvas element can be an image for Fabric.Image, you can find an Edge detection solution for native canvas and then use that native canvas on a Fabric.Image like this image:myNativeCanvas.
[Addition: added a demo]
Here's example code and a demo showing how to:
Use a native canvas to apply Sobel Edge Detection to an image and
Use that native canvas as the image source for a Fabric.Image
// load an image
var image=new Image();
image.crossOrigin='anonymous';
image.onload=start;
image.src="https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start(){
// apply Sobel Edge Detection
// return ImageData of the filtered canvas
var grayscale = Filters.filterImage(Filters.grayscale, image);
var vertical = Filters.convoluteFloat32(grayscale,
[ -1, 0, 1,
-2, 0, 2,
-1, 0, 1 ]);
var horizontal = Filters.convoluteFloat32(grayscale,
[ -1, -2, -1,
0, 0, 0,
1, 2, 1 ]);
var final_image = Filters.createImageData(vertical.width, vertical.height);
for (var i=0; i<final_image.data.length; i+=4){
// make the vertical gradient red
var v = Math.abs(vertical.data[i]);
final_image.data[i] = v;
// make the horizontal gradient green
var h = Math.abs(horizontal.data[i]);
final_image.data[i+1] = h;
// and mix in some blue for aesthetics
final_image.data[i+2] = (v+h)/4;
final_image.data[i+3] = 255; // opaque alpha
}
// put the filtered imageData on an in-memory canvas
var memCanvas = document.createElement('canvas');
memCanvas.width=image.width;
memCanvas.height=image.height;
memCanvas.getContext('2d').putImageData(final_image,0,0);
// use the in-memory canvas as an image source for a Fabric.Image
var canvas = new fabric.Canvas('canvas');
var imgElement = document.getElementById('my-image');
var imgInstance = new fabric.Image(memCanvas,{left:10,top:10});
canvas.add(imgInstance);
}
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }
<script src="https://dl.dropboxusercontent.com/u/139992952/multple/filters.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<h4>Original Image</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/sun.png'>
<h4>FabricJS image with Sobel filter applied</h4>
<canvas id="canvas" width=300 height=200></canvas>
And here is the Filters.js script used in the demo:
// Attribution: http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
Filters = {};
Filters.getPixels = function(img) {
var c,ctx;
if (img.getContext) {
c = img;
try { ctx = c.getContext('2d'); } catch(e) {}
}
if (!ctx) {
c = this.getCanvas(img.width, img.height);
ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0);
}
return ctx.getImageData(0,0,c.width,c.height);
};
Filters.getCanvas = function(w,h) {
var c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
};
Filters.filterImage = function(filter, image, var_args) {
var args = [this.getPixels(image)];
for (var i=2; i<arguments.length; i++) {
args.push(arguments[i]);
}
return filter.apply(null, args);
};
Filters.grayscale = function(pixels, args) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
// CIE luminance for the RGB
var v = 0.2126*r + 0.7152*g + 0.0722*b;
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
Filters.brightness = function(pixels, adjustment) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
d[i] += adjustment;
d[i+1] += adjustment;
d[i+2] += adjustment;
}
return pixels;
};
Filters.threshold = function(pixels, threshold) {
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
var v = (0.2126*r + 0.7152*g + 0.0722*b >= threshold) ? 255 : 0;
d[i] = d[i+1] = d[i+2] = v
}
return pixels;
};
Filters.tmpCanvas = document.createElement('canvas');
Filters.tmpCtx = Filters.tmpCanvas.getContext('2d');
Filters.createImageData = function(w,h) {
return this.tmpCtx.createImageData(w,h);
};
Filters.convolute = function(pixels, weights, opaque) {
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side/2);
var src = pixels.data;
var sw = pixels.width;
var sh = pixels.height;
var w = sw;
var h = sh;
var output = Filters.createImageData(w, h);
var dst = output.data;
var alphaFac = opaque ? 1 : 0;
for (var y=0; y<h; y++) {
for (var x=0; x<w; x++) {
var sy = y;
var sx = x;
var dstOff = (y*w+x)*4;
var r=0, g=0, b=0, a=0;
for (var cy=0; cy<side; cy++) {
for (var cx=0; cx<side; cx++) {
var scy = Math.min(sh-1, Math.max(0, sy + cy - halfSide));
var scx = Math.min(sw-1, Math.max(0, sx + cx - halfSide));
var srcOff = (scy*sw+scx)*4;
var wt = weights[cy*side+cx];
r += src[srcOff] * wt;
g += src[srcOff+1] * wt;
b += src[srcOff+2] * wt;
a += src[srcOff+3] * wt;
}
}
dst[dstOff] = r;
dst[dstOff+1] = g;
dst[dstOff+2] = b;
dst[dstOff+3] = a + alphaFac*(255-a);
}
}
return output;
};
if (!window.Float32Array)
Float32Array = Array;
Filters.convoluteFloat32 = function(pixels, weights, opaque) {
var side = Math.round(Math.sqrt(weights.length));
var halfSide = Math.floor(side/2);
var src = pixels.data;
var sw = pixels.width;
var sh = pixels.height;
var w = sw;
var h = sh;
var output = {
width: w, height: h, data: new Float32Array(w*h*4)
};
var dst = output.data;
var alphaFac = opaque ? 1 : 0;
for (var y=0; y<h; y++) {
for (var x=0; x<w; x++) {
var sy = y;
var sx = x;
var dstOff = (y*w+x)*4;
var r=0, g=0, b=0, a=0;
for (var cy=0; cy<side; cy++) {
for (var cx=0; cx<side; cx++) {
var scy = Math.min(sh-1, Math.max(0, sy + cy - halfSide));
var scx = Math.min(sw-1, Math.max(0, sx + cx - halfSide));
var srcOff = (scy*sw+scx)*4;
var wt = weights[cy*side+cx];
r += src[srcOff] * wt;
g += src[srcOff+1] * wt;
b += src[srcOff+2] * wt;
a += src[srcOff+3] * wt;
}
}
dst[dstOff] = r;
dst[dstOff+1] = g;
dst[dstOff+2] = b;
dst[dstOff+3] = a + alphaFac*(255-a);
}
}
return output;
};
//
function runFilter(id, filter, arg1, arg2, arg3) {
var c = document.getElementById(id);
var s = c.previousSibling.style;
var b = c.parentNode.getElementsByTagName('button')[0];
if (b.originalText == null) {
b.originalText = b.textContent;
}
if (s.display == 'none') {
s.display = 'inline';
c.style.display = 'none';
b.textContent = b.originalText;
} else {
var idata = Filters.filterImage(filter, img, arg1, arg2, arg3);
c.width = idata.width;
c.height = idata.height;
var ctx = c.getContext('2d');
ctx.putImageData(idata, 0, 0);
s.display = 'none';
c.style.display = 'inline';
b.textContent = 'Restore original image';
}
}
//
sobel = function() {
runFilter('sobel', function(px){
px = Filters.grayscale(px);
var vertical = Filters.convoluteFloat32(px,
[-1,-2,-1,
0, 0, 0,
1, 2, 1]);
var horizontal = Filters.convoluteFloat32(px,
[-1,0,1,
-2,0,2,
-1,0,1]);
var id = Filters.createImageData(vertical.width, vertical.height);
for (var i=0; i<id.data.length; i+=4) {
var v = Math.abs(vertical.data[i]);
id.data[i] = v;
var h = Math.abs(horizontal.data[i]);
id.data[i+1] = h
id.data[i+2] = (v+h)/4;
id.data[i+3] = 255;
}
return id;
});
}

Javascript canvas draw rect not working, trying to make a game board

So I made a program that is supposed to make an empty 2d game board using stroke rect or draw img. Here it is (using stroke rect):
window.onload = function() {
//set up the canvas items
var canvas = document.getElementById("paper");
var emptySquare = canvas.getContext("2d");
var player = canvas.getContext("2d");
var background = canvas.getContext("2d");
//An empty game board, with basic stats
var boardArray = [];
var rowNum = 7;
var colNum = 7;
//Makes the board with the empty squares
for (i = 0; i < colNum; i++) {
for (x = 0; x < rowNum; x++) {
boardArray.push([colNum*10, rowNum*10]);
}
}
//This is the png of an empty board part of an array
var emptySquareImg = new Image();
emptySquareImg.src = "border.png";
function displayBoard() {
background.fillStyle = "rgb(0, 0, 0)";
background.fillRect(0, 0, canvas.width, canvas.height);
for (x = 0; x < boardArray.length; x++) {
for (y = 0; y < x.length; y++) {
emptySquare.beginPath();
emptySquare.lineWidth = "4";
emptySquare.strokeStyle = "rgb(200, 34, 22)";
emptySquare.rect(boardArray[x], boardArray[y], 10, 10)
emptySquare.stroke();
}
}
}
displayBoard();
}
It does not display anything except the black background. It also throws no errors, which is sort of weird. Thank you for any help, and I can soon make my little board game!
There are a few issues with your loops and generation of the array of squares. Remember to use the var keyword when setting up for-loops in javascript. Otherwise the variable will not be in the local scope and you probably won't get what you expect. Especially with x in your case since it's used in two loops.
http://jsfiddle.net/mfohao5x/
window.onload = function() {
var canvas = document.getElementById("paper");
var emptySquare = canvas.getContext("2d");
var player = canvas.getContext("2d");
var background = canvas.getContext("2d");
var boardArray = [];
var rowNum = 7;
var colNum = 7;
// probably worth defining the width and height of cells here
var width = 10;
var height = 10;
// remember to include the keyword "var"
for (var i = 0; i < rowNum; i++) {
// add a new row to boardArray
boardArray.push([]);
for (var x = 0; x < colNum; x++) {
// add your values for this square within this row
boardArray[i].push([i*width, x*height]);
}
}
//console.log(boardArray);
var emptySquareImg = new Image();
emptySquareImg.src = "border.png";
function displayBoard() {
background.fillStyle = "rgb(0, 0, 0)";
background.fillRect(0, 0, canvas.width, canvas.height);
for (var x = 0; x < boardArray.length; x++) {
// get the row here and then iterate through it
var row = boardArray[x];
for (var y = 0; y < row.length; y++) {
// now row[y] will give you your square
emptySquare.beginPath();
emptySquare.lineWidth = "4";
emptySquare.strokeStyle = "rgb(200, 34, 22)";
// use row[y][0] and row[y][1] to position the rect
emptySquare.rect(row[y][0], row[y][1], width, height);
emptySquare.stroke();
}
}
}
displayBoard();
}
Here's your code with adjusted loops. boardArray.push([colNum*10, rowNum*10]); is changed to boardArray.push([i*10, x*10]);. boardArray[x], boardArray[y] is changed to arr[0], arr[1].
window.onload = function() {
//set up the canvas items
var canvas = document.getElementById("paper");
var emptySquare = canvas.getContext("2d");
var player = canvas.getContext("2d");
var background = canvas.getContext("2d");
//An empty game board, with basic stats
var boardArray = [];
var rowNum = 7;
var colNum = 7;
//Makes the board with the empty squares
for (i = 0; i < colNum; i++) {
for (x = 0; x < rowNum; x++) {
boardArray.push([i*10, x*10]);
}
}
//This is the png of an empty board part of an array
var emptySquareImg = new Image();
emptySquareImg.src = "border.png";
function displayBoard() {
background.fillStyle = "rgb(0, 0, 0)";
background.fillRect(0, 0, canvas.width, canvas.height);
for (x = 0; x < colNum; x++) {
for (y = 0; y < rowNum; y++) {
emptySquare.beginPath();
emptySquare.lineWidth = "4";
emptySquare.strokeStyle = "rgb(200, 34, 22)";
var arr = boardArray[y+x*colNum];
emptySquare.rect(arr[0], arr[1], 10, 10)
emptySquare.stroke();
}
}
}
displayBoard();
}
<canvas id='paper'></canvas>

Categories

Resources