[Edit]
+
0
-
0
JavaScript - animate image rotation (rotation around: image center, image let-top corner, indicated point)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79<!doctype html> <html> <head> <style> canvas { border: 1px solid gray; } </style> </head> <body> <canvas id="my-canvas" width="600" height="600"></canvas> <script> var RADIAN = Math.PI / 180; function toRadians(degrees) { return degrees * RADIAN; } // Draws image in indicated position rotated around origin point (originX, originY). // Hint: when we want to rotate around image center point, origin point should be: // originX = imageX + image.width / 2; // originY = imageY + image.height / 2; // function drawRotated$1(context, image, imageX, imageY, originX, originY, degrees) { var radians = toRadians(degrees); context.save(); // saves current transformation matrix (state) context.translate(+originX, +originY); context.rotate(radians); // rotates the image around origin point by used translations context.translate(-originX, -originY); context.drawImage(image, imageX, imageY); // draws the image in the position (imageX, imageY) context.restore(); // restores saved transformation matrix (state) } // Draws image in indicated position rotated around relative origin point (originX, originY). // Origin point is measured from let-top image corner. // Hint: when we want to rotate around image center point, origin point should be: // originX = image.width / 2; // originY = image.height / 2; // function drawRotated$2(context, image, imageX, imageY, originX, originY, degrees) { drawRotated$1(context, image, imageX, imageY, imageX + originX, imageY + originY, degrees); } // Draws image in indicated position rotated around image center. // function drawRotated$3(context, image, imageX, imageY, degrees) { // we rotate image around image center (0.5 * image.width, 0.5 * image.height) var originX = 0.5 * image.width; var originY = 0.5 * image.height; drawRotated$2(context, image, imageX, imageY, originX, originY, degrees); } // Usage example: var canvas = document.querySelector('#my-canvas'); var context = canvas.getContext('2d'); var image = new Image(); image.onload = function() { var degrees = 0; setInterval(function () { context.clearRect(0, 0, canvas.width, canvas.height); drawRotated$3(context, image, 50, 50, degrees); // image rotated around image center drawRotated$2(context, image, 450, 150, 0, 0, degrees); // image rotated around image left-top corner - point (0, 0) on the image drawRotated$1(context, image, 450, 450, 450, 150, degrees); // image rotated around some point (450, 150) degrees += 1; }, 10) }; image.src = 'https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png'; </script> </body> </html>
Reset