HTML5 canvas how to change putImageData scale

user3778390 picture user3778390 · Jun 26, 2014 · Viewed 13.6k times · Source

How to change putImageData scale with scale(1.5, 1.5) not working..

var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
context.clearRect(0, 0, canvas.width, canvas.height);
context.scale(1.5, 1.5);
context.putImageData(imageData, 0, 0);

Answer

markE picture markE · Jun 28, 2014

Correct, your code will not scale the existing drawings.

context.scale only affects new drawings, not existing drawings.

context.putImageData will put the saved original pixels back on the canvas, but putImageData is not a drawing command so its results will not be scaled.

To scale existing pixels you have to save the pixels to an entity outside of your canvas. The outside entity could be a new Image element or a second Canvas element.

Example code and a Demo: http://jsfiddle.net/m1erickson/p5nEE/

// canvas related variables
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");

// draw a test square
context.fillStyle="red";
context.fillRect(0,0,50,50);

// create an image from the canvas
// clear & scale the canvas
// draw the image to the canvas
var imageObject=new Image();
imageObject.onload=function(){

    context.clearRect(0,0,canvas.width,canvas.height);
    context.scale(1.2,1.2);
    context.drawImage(imageObject,0,0);

}
imageObject.src=canvas.toDataURL();