HTML5 Game - Draw tile on mouse click on image, tile stamper

Description

Draw tile on mouse click on image, tile stamper

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { /*from   w  ww . ja v a  2  s .co m*/
  border:1px solid #03F; 
  background:#CFC; 
} 
</style> 
</head> 
<body> 
<canvas id="canvas" width="640" height="480"></canvas> 
<script> 

  let context = document.getElementById('canvas').getContext('2d'); 
  let mouseX;
  let mouseY;
  
  
  let tileSheet=new Image();
  tileSheet.addEventListener('load', eventSheetLoaded , false);
  tileSheet.src="http://java2s.com/style/download.png";
  
  
  let imageData=context.createImageData(32,32);
  
  function eventSheetLoaded() {
    startUp();
  }

  function startUp(){
    context.fillStyle="#aaaaaa";
    context.fillRect(0,0,256,256);
    drawTileSheet();
  }
  
  function drawTileSheet(){
    context.drawImage(tileSheet, 0, 0);
    
  }
  
  function highlightTile(tileId,x,y){
    context.fillStyle="#aaaaaa";
    context.fillRect(0,0,256,128);
    drawTileSheet();
    
    imageData=context.getImageData(x,y,32,32);
    //loop through imageData.data. Set every 4th value to a new value
    for (j=3; j< imageData.data.length; j+=4){
      imageData.data[j]=128;
    }
    
    
    let startX=Math.floor(tileId % 8) *32;
    let startY=Math.floor(tileId / 8) *32;
    context.strokeStyle="red";
    context.strokeRect(startX,startY,32,32)
  }
  
  function onMouseMove(e) {
    mouseX=e.clientX-document.getElementById('canvas').offsetLeft;
    mouseY=e.clientY-document.getElementById('canvas').offsetTop;
        
  }
  
  function onMouseClick(e) {
    console.log("click: " + mouseX + "," + mouseY);
    if (mouseY < 128){
      //find tile to highlight
      let col=Math.floor(mouseX / 32);
      let row=Math.floor(mouseY / 32)
      let tileId=(row*7)+(col+row);
      highlightTile(tileId,col*32,row*32)
    }else{
      let col=Math.floor(mouseX / 32);
      let row=Math.floor(mouseY / 32)
      
      context.putImageData(imageData,col*32,row*32);
      
      
    }
  }
  
  document.getElementById('canvas').addEventListener("mousemove", onMouseMove, false);
  document.getElementById('canvas').addEventListener("click", onMouseClick, false);


</script> 



</body> 
</html>

Related Topic