<script> window.onload = function() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); ////////////////////////////////////// start here //// DEFINE VARIABLES var x = 100; var y = 50; var w = 75; var h = 75; var tx = w/2; var ty = h/2; var rx = - tx; var ry = - ty; var a = Math.PI / 4; ///// GEOMETRIC TRANSFORMATIONS //// FIRST TRANSLATE TO TOP LEFT CORNER OF SQUARE //// these are the new (0,0) coordinates context.translate(x, y); //// THEN TRANSLATE TO CENTER OF SQUARE context.translate(tx, ty); // NEW (0,0); //// THEN ROTATE context.rotate(a); // IF YOU INVERT THE ORDER // THE X and Y AXIS ARE ALSO ROTATED // WE ARE ROTATING USING CENTER OF SQUARE AS AXIS ///// COLOR STYLES var grd = context.createLinearGradient(rx,ry,rx+w,ry+h); grd.addColorStop(0.1, "red"); grd.addColorStop(0.5, "cyan"); grd.addColorStop(0.9, "black"); context.fillStyle = grd; context.fill(); context.fillRect(rx,ry,w,h); document.getElementById("display").innerHTML += "x = " + x + " | y = " + y + " | tx = " + tx + " | ty = " + ty + " | rx = " + rx + " | ry = " + ry; ////////////////////////////////////// end here }; </script>