Cross-browser image rotation with JavaScript and CSS
Here is a cross-browser implementation of image rotation. The code uses IE filters and Mozilla/Opera/Safari Canvas object:
The source code:
<script type="text/javascript"> (function (element, event, handler) { if (element.addEventListener) element.addEventListener(event, handler, false); else if (element.attachEvent) element.attachEvent('on' + event, handler); else element['on' + event] = handler; })(window, 'load', function () { document.img = (function (id, src, width, height) { var _element = document.getElementById(id); var _canvas = document.createElement('canvas'); if (_canvas.getContext) { // Opera/Safari/FireFox code: _element.appendChild(_canvas); _canvas.setAttribute('width', width); _canvas.setAttribute('height', height); var _center = { 'x' : Math.round(width / 2), 'y' : Math.round(height / 2) }; var _ctx = _canvas.getContext('2d'); var _img = new Image(); _img.onload = function () { _ctx.translate(_center.x, _center.y); _ctx.drawImage(_img, -1 * _center.x, -1 * _center.y); }; _img.src = src; return { 'rotateCW' : function () { _ctx.rotate(Math.PI/2); _ctx.drawImage(_img, -1 * _center.x, -1 * _center.y); }, 'rotateCCW' : function () { _ctx.rotate(-Math.PI/2); _ctx.drawImage(_img, -1 * _center.x, -1 * _center.y); } }; } // IE code: var _rotation = 0; var _filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation={0})'; _element.style.width = width + 'px'; _element.style.height = height + 'px'; _element.style.background = 'url(\'' + src + '\')'; _element.style.backgroundPosition = 'center center'; _element.style.backgroundRepeat = 'no-repeat'; return { 'rotateCW' : function () { _rotation = (_rotation + 1) % 4; _element.style.filter = _filter.replace('{0}', _rotation); }, 'rotateCCW' : function () { _rotation = (4 + _rotation - 1) % 4; _element.style.filter = _filter.replace('{0}', _rotation); } }; })('image', '/files/n152.sample.png', 150, 150); }); </script> <button onclick="document.img.rotateCCW()" style="font-family: arial;">←</button> <button onclick="document.img.rotateCW()" style="font-family: arial;">→</button> <div id="image" style="margin: 1em;"></div>
Safari
Not working on Safari 3.1.1 :( any hints?
Sorry, my mistake.
I've updated the code, should work with Safari.