在 html 中旋转图像源中的图像

有没有一种方法,我可以添加我的图像源代码,可以旋转我的图像?

就像这样:

<img id="image_canv" src="/image.png" rotate="90">

我使我的图像动态,所以我想知道,如果我可以附加一些额外的代码来旋转它,如果我想要的。

439502 次浏览

If your rotation angles are fairly uniform, you can use CSS:

<img id="image_canv" src="/image.png" class="rotate90">

CSS:

.rotate90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}

Otherwise, you can do this by setting a data attribute in your HTML, then using Javascript to add the necessary styling:

<img id="image_canv" src="/image.png" data-rotate="90">

Sample jQuery:

$('img').each(function() {
var deg = $(this).data('rotate') || 0;
var rotate = 'rotate(' + deg + 'deg)';
$(this).css({
'-webkit-transform': rotate,
'-moz-transform': rotate,
'-o-transform': rotate,
'-ms-transform': rotate,
'transform': rotate
});
});

Demo:

http://jsfiddle.net/verashn/6rRnd/5/

This might be your script-free solution: http://davidwalsh.name/css-transform-rotate

It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.

That means that if you don't care for old IEs (the bane of web designers) you can skip the -ms- and -moz- prefixes to economize space.

However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need -webkit-, and there's a still-big cult following of pre-Next Opera and using -o- is sensate.

This CSS seems to work in Safari and Chrome:

div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}

and in the body:

<div id="div2"><img src="image.jpg"  ></div>

But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.

You can do this:

<img src="your image" style="transform:rotate(90deg);">

it is much easier.