0
$('#myCanvas').click(function (e) { //Default mouse Position 
        console.log(e.pageX);
$("#myCanvas2").attr("width", e.pageX );
$("#myCanvas3").attr("width", e.pageX );
        var imageData = context.getImageData(0, 0, e.pageX,400);
context2.putImageData(imageData,0,0);
context3.putImageData(imageData,0,0);
context.clearRect ( 0 , 0 , 2000 , 2000 );
$("#myCanvas3").css("scale", "(-1, 1)" );
$("#myCanvas3").css("transform", "scale(-1,1)");

 var canvas4 = document.getElementById('myCanvas4');
 var context4 = canvas4.getContext('2d');
 context4.drawImage( myCanvas2, 0,0 );
 context4.drawImage(myCanvas3, e.pageX,0 );


context3.scale(3,3);
    });

I am trying to scale my canvas with the scale command.

What am I doing wrong?

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • What's going wrong exactly? Do you have a link to an example? – Blake Simpson Jul 08 '14 at 07:26
  • It just does not seem to scale. I have defined my context's just fine outside the function. The only thing that seems to not be working is the scale command. – nicholaswmin Jul 08 '14 at 07:27
  • This thread should help: [How to scale an imageData in HTML canvas?](http://stackoverflow.com/questions/3448347/how-to-scale-an-imagedata-in-html-canvas) – imcg Jul 08 '14 at 08:55

1 Answers1

0

I'm not clear what you're trying to do, but these thoughts come to mind:

To get an accurate canvas mouse position, calculate relative to the canvas element:

$('myCanvas').click(function(e){

    var BB=canvas.getBoundingClientRect();
    var mouseX=parseInt(e.clientX-BB.left);
    var mouseY=parseInt(e.clientY-BB.top);
}

About mixing CSS and Canvas:

  • CSS scale will operate on the center of the element.
  • Canvas scale will operate from the origin (the origin defaults to 0,0).
  • CSS scaling will not affect Canvas drawing. So if you "flip" using CSS scaling and then you draw the flipped element to a canvas, the resulting canvas drawing is not flipped.
  • Changing the canvas element width will also automatically clear the canvas content.
  • Changing CSS width will retain the canvas content, but will "stretch" the existing pixels into the new width (the content will appear deformed).

Canvas scaling commands only affect drawings done after the scale command. So your context3.scale(3,3) will not affect anything you have previously drawn on myCanvas3.

Here's how to horizontally flip an image on a canvas element:

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

var img=document.getElementById("theImg");
var iw=img.width;
var ih=img.height;
var canvas2=document.getElementById('myCanvas2');
var context2=canvas2.getContext('2d');
canvas2.width=iw;
canvas2.height=ih;
context2.save();
context2.translate(iw,0);
context2.scale(-1,1);
context2.drawImage(img,0,0);
context2.restore();

enter image description here

markE
  • 102,905
  • 11
  • 164
  • 176