Last active
March 26, 2016 03:28
-
-
Save sortofsleepy/16d227a1411b80a7ce7b to your computer and use it in GitHub Desktop.
Converts copy you write in a canvas 2D context to an array of THREE.Vector2s (but could easily be modded to just return a regular array)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple class for quickly creating positions | |
* for use in a mesh or for whatever other purpose you might want. | |
*/ | |
class TypeBuilder { | |
constructor(string="Hello",width=140,height=100){ | |
this.canvas = document.createElement("canvas"); | |
this.canvas.width = width; | |
this.canvas.height = height; | |
this.canvas.style.cssText = "position:relative;z-index:999" | |
this.ctx = this.canvas.getContext('2d'); | |
this.ctx.font = "50px Helvetica"; | |
this.textDimensions = this.ctx.measureText(string); | |
this.width = width; | |
this.height = height; | |
this.string = string; | |
} | |
/** | |
* append to specified node - really just used for testing | |
* @param node | |
*/ | |
appendTo(node){ | |
node.appendChild(this.canvas); | |
} | |
/** | |
* Write out the text | |
*/ | |
write(copy=""){ | |
copy = copy !== "" ? copy : this.string; | |
let x = this.width / 2 - (this.textDimensions.width / 2); | |
this.ctx.fillStyle = "#000"; | |
this.ctx.fillRect(0,0,this.width,this.height); | |
this.ctx.fillText(copy,x,50); | |
} | |
/** | |
* Pull the text pixels. Extract points of black | |
*/ | |
readPixels(x=0,y=0,width=140,height=100){ | |
let imgData = this.ctx.getImageData(x,y,width,height); | |
let len = imgData.length; | |
var buffer32 = new Uint32Array(imgData.data.buffer) | |
let positions = []; | |
for (var y = 0; y < this.height; y ++) { | |
for (var x = 0; x < this.width; x ++) { | |
let val = buffer32[y * this.width + x]; | |
if(val !== 0){ | |
positions.push(new THREE.Vector2(x,y)); | |
} | |
} | |
} | |
return positions; | |
} | |
} | |
export default TypeBuilder; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment