Scaling Canvas Down - Javascript Canvas

Javascript examples for Canvas:Example

Description

Scaling Canvas Down

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
      <style id="compiled-css" type="text/css">

canvas {/*  ww  w.ja va  2 s  . c o  m*/
   border: 2px solid red;
}


      </style> 
      <script type="text/javascript">
    window.onload=function(){

canvas.width = 100;
canvas.height = 100;

const ctx = canvas.getContext("2d");
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 100, 100);
ctx.fillStyle = "#ff0000";
ctx.fillRect(40, 40, 20, 20);

const imageData = ctx.getImageData(0, 0, 1, 1);
const pixel32 = new Uint32Array(imageData.data.buffer);
pixel32[0] = 0;
ctx.putImageData(imageData, 50, 50);

$("#button").click(function() {
  ScaleCanvas(canvas.width / 2, canvas.height / 2, .5, .5);
});

function ScaleCanvas(width, height, xScale, yScale) {
   const initialWidth = canvas.width;
   const initialHeight = canvas.height;

  const imageData = ctx.getImageData(0, 0, initialWidth, initialHeight);

  const newCanvas = $("<canvas>")
    .attr("width", initialWidth)
    .attr("height", initialHeight)[0];

  newCanvas.getContext("2d").putImageData(imageData, 0, 0);

  ctx.canvas.width = width;
  ctx.canvas.height = height;

  ctx.scale(xScale, yScale);

  ctx.drawImage(newCanvas, 0, 0);
}
    }

      </script> 
   </head> 
   <body> 
      <canvas id="canvas"></canvas> 
      <button id="button">Scale Down Canvas</button>  
   </body>
</html>

Related Tutorials