Michael Mikhjian
Michael Mikhjian

Reputation: 2794

HTML5 canvas: Rotate cropped image within bounds on single canvas

I'm trying to rotate an image, crop that, render to canvas; all in a single canvas layer. I don't think it's possible with the provided API, I think I do have to render a 2nd canvas layer and then render it back to the original layer, correct?

As far as I know, it's a very linear process for canvas: [translate to middle of image], [apply rotation], [rotate back to top left], [draw image with crop values].

Upvotes: 1

Views: 984

Answers (2)

Michael Mikhjian
Michael Mikhjian

Reputation: 2794

Welp I figured it out shortly I realized that there's a Clip tool, wahoo!

Basically the patch (for those who come here) is:

You need to set a path and set up the boundary, then close & clip the path, then apply rotation, then apply drawImage (don't even need to apply the crops to it).

So i.e. (v = object; v.p = position; v.c = crop size; v.s= image size)

            vb.ctx.beginPath();
            vb.ctx.moveTo( v.p[0], v.p[1] );
            vb.ctx.lineTo( v.p[0]+v.c[0], v.p[1] );
            vb.ctx.lineTo( v.p[0]+v.c[0], v.c[1]+v.p[1] );
            vb.ctx.lineTo( v.p[0], v.c[1]+v.p[1] );
            vb.ctx.lineTo( v.p[0], v.p[1] );

            vb.ctx.closePath();
            vb.ctx.clip();

            vb.ctx.translate( v.p[0]+ (v.c[0]/2), v.p[1] + (v.c[1]/2) );
            vb.ctx.rotate( v.rot );
            vb.ctx.translate( 0-(v.p[0]+ (v.c[0]/2)) , 0-(v.p[1] + (v.c[1]/2)) );

            vb.ctx.drawImage( v.dom, v.p[0], v.p[1], v.s[0], v.s[1] );

Upvotes: 2

markE
markE

Reputation: 105015

You can simultaneously rotate and crop a source image onto a canvas like this:

enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

ctx.fillStyle='red';
ctx.globalAlpha=0.50;
ctx.fillRect(50,50,150,40);
ctx.fillStyle='black';
ctx.globalAlpha=1.00;
ctx.fillText("Crop Me!",55,65);

var img=new Image();
img.onload=function(){
  ctx.translate(150,150);
  ctx.scale(2,2);
  ctx.rotate(Math.PI/4);
  ctx.drawImage(img,50,50,75,20, -75/2,-20/2,75,20);
};
img.src=canvas.toDataURL();
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Upvotes: 0

Related Questions