Ankirama Ankirama - 3 months ago 7
Javascript Question

How to apply canvas transformation on multiple images

I'm playing with

canvas
in
HTML5
and
Javascript
and I have a problem:

I'd like to apply tranformations used on the current image to multiple images.

What I did:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var img = new Image();
img.onload = function() {
//transformation stuff like:
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, -img.width / 2, -img.height / 2, img.width, img.height);
ctx.beginPath();
ctx.lineTo(42, 42);
ctx.stroke();
ctx.lineTo(42, 24);
ctx.stroke();
...
ctx.rotate(Math.PI / 2);
...
};
img.src = //base64Img;


So I will apply a lot of tranformations like draw some lines, crop, zoomIn etc...
How can I apply this to multiple files (more than 200) once (when these tranformations are done) ?

Obviously, it will be done in multiples functions like a function to rotate, to draw a line etc.

Thank you for your help.

Answer

enter image description here

Put your transformations, path drawings & image drawing into a function with arguments that tell the function how each image will be treated:

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

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png";
function start(){

  // Note: img coordinates are [centerX,centerY] rather than the usual [left,top]
  drawTransformedImage(img,25,50,0,.75);
  drawTransformedImage(img,75,50,Math.PI*1/6,1);
  drawTransformedImage(img,150,50,Math.PI*2/6,2);
  drawTransformedImage(img,225,50,Math.PI*3/6,1);
  drawTransformedImage(img,275,50,Math.PI*4/6,.5);

}

function drawTransformedImage(img,cx,cy,radAngle,scale){
  // save incoming styling
  var lw=ctx.lineWidth;
  var ss=ctx.strokeStyle;
  // cache often used half-sizes
  var iwHalf=img.width/2;
  var ihHalf=img.height/2;
  ctx.lineWidth=2;
  // do the specified transformations
  ctx.translate(cx,cy);
  ctx.rotate(radAngle);
  ctx.scale(scale,scale);
  // draw the image
  ctx.drawImage(img,-iwHalf,-ihHalf);
  // stroke some paths
  ctx.beginPath();
  ctx.moveTo(-iwHalf,ihHalf);
  ctx.lineTo(-iwHalf,-ihHalf);
  ctx.strokeStyle='orange';
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(-iwHalf,-ihHalf);
  ctx.lineTo(+iwHalf,-ihHalf);
  ctx.strokeStyle='blue';
  ctx.stroke();
  // clean up: reset transformations and stylings
  ctx.setTransform(1,0,0,1,0,0);
  ctx.lineWidth=lw;
  ctx.strokeStyle=ss;
}
body{ background-color: white; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=150></canvas>

Comments