From 99a54eeb132de71c961d598069010e48109e8bce Mon Sep 17 00:00:00 2001 From: Gator Date: Tue, 20 Dec 2022 11:59:48 +0100 Subject: [PATCH] wip picture to board --- src/components/CanvasBoard.vue | 23 +++++++++++++++++++++-- src/modules/picture.js | 9 ++++----- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/components/CanvasBoard.vue b/src/components/CanvasBoard.vue index 59dde32..545ef5b 100644 --- a/src/components/CanvasBoard.vue +++ b/src/components/CanvasBoard.vue @@ -196,7 +196,7 @@ // draw 2d automaton from an uploaded picture. // use the picture representation as an initial state draw2dPicture() { - // get image data by drawing it on a work canvas + // draw image on canvas this.ctx.fillStyle = "black"; this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight); this.ctx.drawImage( @@ -207,6 +207,7 @@ this.picture.height ); + // get image data from canvas const imgData = this.ctx.getImageData( 0, 0, @@ -214,10 +215,28 @@ this.canvasHeight ); + // draw the image back on the work canvas with the dimensions of the board + this.workCtx.drawImage( + this.picture, + 0, + 0, + this.boardWidth, + this.boardHeight + ); + + // get the resized image data from work canvas + const resized = this.workCtx.getImageData( + 0, + 0, + this.boardWidth, + this.boardHeight + ); + // convert the image into a 2D board of boolean based on pixel value this.lastBoard = Object.freeze( - picToBoard(imgData.data, this.canvasWidth, this.canvasHeight) + picToBoard(resized.data, this.boardWidth, this.boardHeight) ); + this.toggleStop(); }, // stop drawing routines and clear the canvas diff --git a/src/modules/picture.js b/src/modules/picture.js index b3c9db1..6e0e097 100644 --- a/src/modules/picture.js +++ b/src/modules/picture.js @@ -28,11 +28,10 @@ export function picToBlackAndWhite(pixels, width, height) { // convert an ImageData into a 2D array of boolean (0, 1) values export function picToBoard(pixels, width, height) { const flat = pixels.reduce((acc, pixel, index) => { - if (index % 4 == 0) { - const count = pixels[index] + pixels[index + 1] + pixels[index + 2]; - const value = count >= 255 ? 1 : 0; - acc[index] = value; - } + const i = index * 4; + const count = pixels[i] + pixels[i + 1] + pixels[i + 2]; + const value = count >= 255 ? 1 : 0; + acc[index] = value; return acc; }, []);