HTML5 canvas how to change putImageData scale
Asked Answered
W

1

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);
Washout answered 26/6, 2014 at 11:53 Comment(0)
N
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();
Northamptonshire answered 28/6, 2014 at 16:33 Comment(2)
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 is saying they actually do.Mezzo
@Mezzo 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.Dorie

© 2022 - 2024 — McMap. All rights reserved.