Search code examples
javascripthtmlcanvasscale

Scaling HTML Canvas elements


In my main project I have lots of little canvas elements (think: sprites from a sprite map) and I need to be able to scale them before drawing them to the main canvas. Here is my basic code for this:

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

var miniCanvas = document.createElement('canvas');
var miniCanvasContext = miniCanvas.getContext('2d');

miniCanvasContext.beginPath();
miniCanvasContext.rect(0,0,100,100);
miniCanvasContext.closePath();
miniCanvasContext.fillStyle = 'red';
miniCanvasContext.fill();

miniCanvasContext.scale(2,2);//THIS IS THE PROBLEM


ctx.drawImage(miniCanvas, 100, 100);

This test is up at jsfiddle: JSFIDDLE

Essentially, I need this red square to be increased in size by two times.

Thanks.


Solution

  • The drawImage method has a version that lets you draw the miniCanvas with scaling:

    // the last 2 parameters are scaled Width & scaled Height
    
    // parameters:
    // 1st: the image source
    // 2nd,3rd: the upper-left part of the source to clip from
    // 4th,5th: the width & height to clip from the source
    // 6th,7th: the upper-left part of the canvas to draw the clipped image
    // 8th,9th: the scaled width & height to draw on the canvas
    
    ctx.drawImage(miniCanvas, 0,0,100,100, 0,0,200, 200);