23

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);
Yves M.
  • 29,855
  • 23
  • 108
  • 144
user3778390
  • 375
  • 1
  • 6
  • 16

1 Answers1

29

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();
Yukulélé
  • 15,644
  • 10
  • 70
  • 94
markE
  • 102,905
  • 11
  • 164
  • 176
  • wait, arguments 6 and 7 to putImage can't be used to scale the image up? If not i'm not understanding what the [documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData) is saying they actually do. – Michael Jan 03 '18 at 02:04
  • 1
    @Michael You might be confusing `ctx.drawImage()` whose last 2 arguments do actually scale the result. The way this answer frames it is a good mental model: draw commands like drawImage will respect the scale, put commands don't. – Reed Spool Jan 11 '18 at 20:00