Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas how to change putImageData scale

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);
like image 828
user3778390 Avatar asked Jun 26 '14 11:06

user3778390


1 Answers

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();
like image 76
markE Avatar answered Sep 22 '22 07:09

markE