HTML5 Game - Changing the ViewPort Property of the Image

Introduction

We can use the following drawImage method to change viewport of an image.

context.drawImage(photo, windowX, windowY,windowWidth,windowHeight, 
                          0,0,viewPortWidth,viewPortHeight); 

We can change the ViewPort property of the drawn image by modifying the viewPort Width and viewPortHeight values.

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { // w w  w  .j  av  a2s  .  c o  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 photo=new Image();
  photo.addEventListener('load', eventPhotoLoaded , false);
  photo.src="http://java2s.com/style/download.png";
  
  let windowWidth=500;
  let windowHeight=500;
  let viewPortWidth=200;
  let viewPortHeight=200;
  
  let windowX=0;
  let windowY=0;
  
  function eventPhotoLoaded() {
    drawScreen()
  }

  function drawScreen(){
    context.drawImage(photo, windowX, windowY,windowWidth,windowHeight,0,0,viewPortWidth,viewPortHeight);  
  }
</script> 
</body> 
</html>

Related Topic