Skip to content

Instantly share code, notes, and snippets.

@rosemarystanley
Last active October 16, 2019 14:19
Show Gist options
  • Save rosemarystanley/b319fd6c126d19e7e4120c39625af0c8 to your computer and use it in GitHub Desktop.
Save rosemarystanley/b319fd6c126d19e7e4120c39625af0c8 to your computer and use it in GitHub Desktop.
Load a image to a canvas
/**
* Loads the outline image and draws it on the canvas.
*/
_loadImage = () => {
const image = new Image()
const context = this.canvas.getContext('2d')
context.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
image.onload = () => {
context.drawImage(image, 0, 0, this.canvasWidth, this.canvasHeight)
}
image.src =
this.props.map === 1
? canvasImg1
: this.props.map === 2
? canvasImg2
: canvasImg3
image.width = this.canvasWidth
image.height = this.canvasHeight
}
/**
* Helper method for getting pixel location from a canvas element.
* @param {integer} x x coordinate
* @param {integer} y y coordinate
* @return {string} calculated (numerical) hexcode for the coordinates given on the canvas element.
*/
_getPixel = (x, y) => {
const canvas = document.getElementById('map-layer') // This is the canvas HTML element
const context = canvas.getContext('2d')
const imageData = context.getImageData(x - 1, y - 1, 1, 1) // Returns all the pixel at the x and y coordinates
const d = imageData.data
const rgb = ((d[0] << 16) | (d[1] << 8) | d[2]).toString(16) // Convert the data to RGB.
return ('000000' + rgb).slice(-6) // Convert RGB to Hexcode
}
/**
* Method to determine if given coordinates is a land coolision.
* @param {integer} x [description]
* @param {integer} y [description]
* @return {Boolean} true is "yes land collision"
*/
_isLandCollision = (x, y) => {
// In the game, determine what all the possible next movements are, feed into this method
// Then will return if the game piece is allowed to move to that spot.
// If this returns true, it disables the ability to move that direction.
if (this.state.stage === 2) {
x = parseInt(x, 10)
y = parseInt(y, 10)
}
const color = this._getPixel(x, y)
return color !== 'ffffff'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment