2

Particularly i have this example but it does not seem to work :

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
your browser does not support the canvas tag </canvas>

<canvas id="myCanvas2" width="300" height="150" style="border:1px solid #d3d3d3;">
your browser does not support the canvas tag </canvas>

<script type="text/javascript">

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

var c2=document.getElementById("myCanvas2");
var ctx2=c2.getContext("2d");

ctx.strokeRect(5,5,25,15);
var imageData = ctx.getImageData(0,0,c.width, c.height);


ctx2.putImageData(imageData, 100, 100);
ctx2.scale(2,2);
</script> 

</body>
</html>

Shouldn't the rect get scaled in the second canvas ?

John Papastergiou
  • 999
  • 2
  • 14
  • 29

2 Answers2

2

Try the following code:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

var c2=document.getElementById("myCanvas2");
var ctx2=c2.getContext("2d");

ctx.strokeRect(5,5,25,15);

ctx2.scale(2, 2);
ctx2.drawImage(c, 10, 10);
Maurice
  • 27,582
  • 5
  • 49
  • 62
  • 1
    Answers like "try this" without an explanation are very frowned upon. For future readers, the method here is to create a second canvas element, place the ImageData there, set the scale of the first canvas, then use the drawImage method on the first canvas passing in a reference to the second canvas, the one that contains the target ImageData. – WebWanderer Sep 11 '19 at 17:42
-2

You need to do the transformation before you "write" the image into canvas.

ctx2.scale(2,2);
ctx2.putImageData(imageData, 100, 100);

Then everything should work fine.

kaljak
  • 1,263
  • 1
  • 16
  • 34
  • ImageData is a raw pixel array, and as such is not affected by scale/transformations applied to the canvas - that only affects new drawings sent to the canvas. You would need to copy the data to a new Image or Canvas, which can be adjusted for scale. See http://stackoverflow.com/questions/24429830/html5-canvas-how-to-change-putimagedata-scale – brichins Jun 03 '16 at 15:18