077
LVL 03 — MID DEVELOPERSESSION 077DAY 77

CROP & ROTATE

🎫 PIXELCRAFT-064
Feature | 🟠 Hard | Priority: 🟠 High

Every image editor needs crop and rotate. Build crop with preset ratios (1:1, 16:9, 4:5 for social media), free rotate with real-time preview, and a straighten tool.
CONCEPTS.UNLOCKED
🔄
Canvas Transformations
translate(), rotate(), scale(). These transform the coordinate system, not the pixels. Draw at (0,0) after translating — the transformation matrix handles the rest.
✂️
Selection Rectangle
Draggable crop region with resize handles. Draw a rectangle overlay, let the user drag edges and corners. The area inside gets kept, everything outside gets cut.
🔲
Aspect Ratio Constraints
Lock width:height proportions. 1:1 for Instagram square, 16:9 for YouTube, 4:5 for Instagram portrait. When one dimension changes, the other adjusts automatically.
📐
Rotation Math
Degrees → radians, rotate around center. ctx.translate(cx, cy) → ctx.rotate(angle) → draw at (-w/2, -h/2). The rotate-around-center pattern you'll use everywhere.
↔️
Drag Handles
8 handles for resize, 1 for rotate. Corner handles resize freely (or proportionally with Shift). Edge handles resize one dimension. A handle outside the box rotates.
📱
Social Media Presets
One-click crop ratios. Instagram: 1:1, 4:5, 1.91:1. YouTube: 16:9. Twitter header: 3:1. TikTok: 9:16. Presets save users time and ensure platform compatibility.
HANDS-ON.TASKS
01
Draw Selection Rectangle with Handles
function drawCropOverlay( ctx, crop, canvasW, canvasH ) { // Darken area outside crop ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; ctx.fillRect(0, 0, canvasW, canvasH); // Clear the crop region (show image) ctx.clearRect( crop.x, crop.y, crop.width, crop.height ); // Draw border ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; ctx.strokeRect( crop.x, crop.y, crop.width, crop.height ); // Draw rule-of-thirds grid drawThirdsGrid(ctx, crop); // Draw resize handles const handles = getHandlePositions(crop); handles.forEach(h => { ctx.fillStyle = '#fff'; ctx.fillRect( h.x - 4, h.y - 4, 8, 8); }); } function getHandlePositions(crop) { const { x, y, width: w, height: h } = crop; return [ { x, y, cursor: 'nw-resize' }, { x: x+w/2, y, cursor: 'n-resize' }, { x: x+w, y, cursor: 'ne-resize' }, { x: x+w, y: y+h/2, cursor: 'e-resize' }, { x: x+w, y: y+h, cursor: 'se-resize' }, { x: x+w/2, y: y+h, cursor: 's-resize' }, { x, y: y+h, cursor: 'sw-resize' }, { x, y: y+h/2, cursor: 'w-resize' }, ]; }
02
Aspect Ratio Presets
const CROP_PRESETS = { free: null, square: 1 / 1, portrait: 4 / 5, // Instagram landscape: 16 / 9, // YouTube wide: 1.91 / 1, // Facebook story: 9 / 16, // Stories/Reels twitter: 3 / 1, // Twitter header }; function constrainToRatio( crop, ratio, handle ) { if (!ratio) return crop; // Free crop // Adjust height based on width const newCrop = { ...crop }; if (handle.includes('e') || handle.includes('w')) { newCrop.height = newCrop.width / ratio; } else { newCrop.width = newCrop.height * ratio; } return newCrop; }
03
Apply Crop
function applyCrop( sourceCanvas, crop ) { const output = document.createElement('canvas'); output.width = crop.width; output.height = crop.height; const ctx = output.getContext('2d'); // Draw only the cropped region ctx.drawImage( sourceCanvas, crop.x, crop.y, // source x,y crop.width, // source w crop.height, // source h 0, 0, // dest x,y crop.width, // dest w crop.height // dest h ); return output; }
04
Free Rotate with Preview
function rotateCanvas( sourceCanvas, degrees ) { const radians = degrees * Math.PI / 180; // Calculate new canvas size // to fit rotated image const sin = Math.abs(Math.sin(radians)); const cos = Math.abs(Math.cos(radians)); const w = sourceCanvas.width; const h = sourceCanvas.height; const newW = w * cos + h * sin; const newH = w * sin + h * cos; const output = document.createElement('canvas'); output.width = newW; output.height = newH; const ctx = output.getContext('2d'); // Translate to center, rotate, draw ctx.translate(newW / 2, newH / 2); ctx.rotate(radians); ctx.drawImage( sourceCanvas, -w / 2, -h / 2); return output; }
The rotated image needs a larger canvas to fit — corners stick out. Calculate the new bounds with sin/cos. This is the same math used in CSS transform: rotate().
05
Close the Ticket
git switch -c feature/PIXELCRAFT-064-crop-rotate git add src/ git commit -m "Add crop with presets + free rotate (PIXELCRAFT-064)" git push origin feature/PIXELCRAFT-064-crop-rotate # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Transformations are linear algebra in action.

Every translate, rotate, and scale is a matrix multiplication. The GPU does millions of these per frame.

// The transformation matrix (2D):

| a c e |
| b d f |
| 0 0 1 |

// translate(tx, ty):
e = tx, f = ty

// rotate(θ):
a = cos(θ), c = -sin(θ)
b = sin(θ), d = cos(θ)

// scale(sx, sy):
a = sx, d = sy

// Canvas stacks transformations.
// save() / restore() pushes/pops
// the matrix stack. Same concept
// powers WebGL, game engines, and
// every 3D application in existence.
"Transform Lab"
[A]Add a straighten tool: detect the horizon line (or let the user draw it), then rotate to make it level. Show a grid overlay during straighten to help alignment.
[B]Add flip horizontal and flip vertical. Use ctx.scale(-1, 1) for horizontal flip. Add keyboard shortcuts: H for flip horizontal, V for vertical. Common photo editing operations.
[C]Research perspective transform: CSS perspective() and matrix3d() can create 3D perspective effects. How does Photoshop's Free Transform work? Explore the math behind 4-point perspective correction.
REF.MATERIAL
ARTICLE
MDN Web Docs
translate, rotate, scale, transform matrix, save/restore. The complete Canvas transformation guide with interactive examples.
CANVASTRANSFORMSESSENTIAL
VIDEO
3Blue1Brown
The most beautiful math series on YouTube. Visualizes matrices as transformations of space. After this, you'll see why rotate() is a matrix multiplication.
LINEAR ALGEBRAVISUALESSENTIAL
ARTICLE
MDN Web Docs
The 9-argument form of drawImage: source rectangle → destination rectangle. The essential function for cropping, scaling, and compositing images on Canvas.
CANVASMDNOFFICIAL
VIDEO
The Coding Train
Pixel manipulation, image data, and transformations in Canvas. Hands-on tutorial with creative coding examples.
CANVASTUTORIAL
ARTICLE
Wikipedia
The linear algebra behind 2D and 3D transformations. Rotation matrices, homogeneous coordinates, and affine transforms.
MATHTHEORYCS
// LEAVE EXCITED BECAUSE
One click: crop to 1:1 for Instagram. Drag the slider: rotate to any angle with live preview. The rule-of-thirds grid helps compose the perfect shot. PixelCraft is becoming a real image editor.