Html 如何使用 HTML5 水平翻转图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3129099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:37:39  来源:igfitidea点击:

How to flip images horizontally with HTML5

htmlcanvas

提问by Koerr

In IE, I can use:

在 IE 中,我可以使用:

<img src="http://example.com/image.png" style="filter:FlipH">

to implement an image flip horizontally.

实现图像水平翻转。

Is there any way to flip horizontally in HTML5? (maybe by using canvas?)

有没有办法在 HTML5 中水平翻转?(也许通过使用画布?)

thanks all :)

谢谢大家:)

回答by Buildstarted

canvas = document.createElement('canvas');
canvasContext = canvas.getContext('2d');

canvasContext.translate(width, 0);
canvasContext.scale(-1, 1);
this.canvasContext.drawImage(image, 0, 0);

Here's a snippet from a sprite object being used for testing and it produces the results you seem to expect.

这是用于测试的精灵对象的片段,它产生了您似乎期望的结果。

Here's another site with more details. http://andrew.hedges.name/widgets/dev/

这是另一个包含更多详细信息的站点。http://andrew.hedges.name/widgets/dev/

回答by robertc

You don't need HTML5, it can be done with CSS same as in IE:

你不需要 HTML5,它可以用 CSS 来完成,就像在 IE 中一样:

-moz-transform: scale(-1, 1);
-webkit-transform: scale(-1, 1);
-o-transform: scale(-1, 1);
transform: scale(-1, 1);
filter: FlipH;

回答by DesignConsult

I like Eschers function above. I have made it a little neater and better. I have added flop(vertically) besides flip. Also a possibility to draw/rotate around the centerof the image instead of top left. Finally, the function does not require all arguments. img, x and y are required but the rest are not.

我喜欢上面的埃舍尔函数。我已经把它弄得更整洁更好了。除了翻转之外,我还添加了翻转(垂直)。也可以围绕图像的中心而不是左上角绘制/旋转。最后,该函数不需要所有参数。img、x 和 y 是必需的,但其余的不是。

If you were using something like context.drawImage(...), you can now just use drawImage(...)and add the rotate/flip/flop functionality explained here:

如果你使用的是context.drawImage(...) 之类的东西,你现在可以只使用drawImage(...)并添加这里解释的旋转/翻转/翻转功能:

function drawImage(img, x, y, width, height, deg, flip, flop, center) {

context.save();

if(typeof width === "undefined") width = img.width;
if(typeof height === "undefined") height = img.height;
if(typeof center === "undefined") center = false;

// Set rotation point to center of image, instead of top/left
if(center) {
    x -= width/2;
    y -= height/2;
}

// Set the origin to the center of the image
context.translate(x + width/2, y + height/2);

// Rotate the canvas around the origin
var rad = 2 * Math.PI - deg * Math.PI / 180;    
context.rotate(rad);

// Flip/flop the canvas
if(flip) flipScale = -1; else flipScale = 1;
if(flop) flopScale = -1; else flopScale = 1;
context.scale(flipScale, flopScale);

// Draw the image    
context.drawImage(img, -width/2, -height/2, width, height);

context.restore();
}

Examples:

例子:

var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext("2d"); // i use context instead of ctx

var img = document.getElementById("myImage"); // your img reference here!

drawImage(img, 100, 100); // just draw it 
drawImage(img, 100, 100, 200, 50); // draw it with width/height specified
drawImage(img, 100, 100, 200, 50, 45); // draw it at 45 degrees
drawImage(img, 100, 100, 200, 50, 0, true); // draw it flipped
drawImage(img, 100, 100, 200, 50, 0, false, true); // draw it flopped
drawImage(img, 100, 100, 200, 50, 0, true, true); // draw it flipflopped
drawImage(img, 100, 100, 200, 50, 45, true, true, true); // draw it flipflopped and 45 degrees rotated around the center of the image :-)

回答by Blindman67

Mirror an image or rendering using the canvas.

使用画布镜像图像或渲染。

Note. This can be done via CSS as well.

笔记。这也可以通过 CSS 来完成。



Mirroring

镜像

Here is a simple utility function that will mirror an image horizontally, vertically or both.

这是一个简单的实用函数,可以水平、垂直或同时镜像图像。

function mirrorImage(ctx, image, x = 0, y = 0, horizontal = false, vertical = false){
    ctx.save();  // save the current canvas state
    ctx.setTransform(
        horizontal ? -1 : 1, 0, // set the direction of x axis
        0, vertical ? -1 : 1,   // set the direction of y axis
        x + horizontal ? image.width : 0, // set the x origin
        y + vertical ? image.height : 0   // set the y origin
    );
    ctx.drawImage(image,0,0);
    ctx.restore(); // restore the state as it was when this function was called
}

Usage

用法

mirrorImage(ctx, image, 0, 0, true, false); // horizontal mirror
mirrorImage(ctx, image, 0, 0, false, true); // vertical mirror
mirrorImage(ctx, image, 0, 0, true, true);  // horizontal and vertical mirror


Drawable image.

可绘制的图像。

Many times you will want to draw on images. I like to call them drawable images. To make an image drawable you convert it to a canvas

很多时候你会想要在图像上绘图。我喜欢称它们为可绘制图像。要使图像可绘制,请将其转换为画布

To convert an image to canvas.

将图像转换为画布。

function makeImageDrawable(image){
    if(image.complete){ // ensure the image has loaded
        var dImage = document.createElement("canvas"); // create a drawable image
        dImage.width = image.naturalWidth;      // set the resolution
        dImage.height = image.naturalHeight;
        dImage.style.width = image.style.width; // set the display size
        dImage.style.height = image.style.height; 
        dImage.ctx = dImage.getContext("2d");   // get drawing API
                                                // and add to image
                                                // for possible later use
        dImage.ctx.drawImage(image,0,0);
        return dImage;
    }
    throw new ReferenceError("Image is not complete.");
 }


Putting it all together

把这一切放在一起

 var dImage = makeImageDrawable(image);  // convert DOM img to canvas
 mirrorImage(dImage.ctx, dImage, 0, 0, false, true); // vertical flip
 image.replaceWith(dImage);  // replace the DOM image with the flipped image


More mirrors

更多镜子

If you wish to be able to mirror along an arbitrary line see the answer Mirror along line

如果您希望能够沿任意线镜像,请参阅答案沿线镜像

回答by Escher

I came across this page, and no-one had quite written a function to do what I wanted, so here's mine. It draws scaled, rotated, and flipped images (I used this for rending DOM elements to canvas that have these such transforms applied).

我遇到了这个页面,没有人写过一个函数来做我想做的事,所以这是我的。它绘制缩放、旋转和翻转的图像(我用它来将 DOM 元素渲染到应用了这些变换的画布上)。

var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");
var img = document.getElementById("myimage.jpg"); //or whatever
var deg = 13; //13 degrees rotation, for example
var flip = "true";

function drawImage(img, x, y, width, height, deg, flip){
    //save current context before applying transformations
    ctx.save();
    //convert degrees to radians
    if(flip == "true"){ 
        var rad = deg * Math.PI / 180;
    }else{
        var rad = 2*Math.PI - deg * Math.PI / 180;
    }
    //set the origin to the center of the image
    ctx.translate(x + width/2, y + height/2);
    //rotate the canvas around the origin
    ctx.rotate(rad);
    if(flip == "true"){
        //flip the canvas
        ctx.scale(-1,1);
    }
    //draw the image    
    ctx.drawImage(img, -width/2, -height/2, width, height);
    //restore the canvas
    ctx.restore();
}

回答by Daniel Korenblum

One option is to horizontally flip the pixels of images stored in ImageData objects directly, e.g.

一种选择是直接水平翻转存储在 ImageData 对象中的图像的像素,例如

function flip_image (canvas) {
    var context   = canvas.getContext ('2d') ;
    var imageData = context.getImageData (0, 0, canvas.width, canvas.height) ;
    var imageFlip = new ImageData (canvas.width, canvas.height) ;
    var Npel      = imageData.data.length / 4 ;

    for ( var kPel = 0 ; kPel < Npel ; kPel++ ) {
        var kFlip      = flip_index (kPel, canvas.width, canvas.height) ;
        var offset     = 4 * kPel ;
        var offsetFlip = 4 * kFlip ;
        imageFlip.data[offsetFlip + 0] = imageData.data[offset + 0] ;
        imageFlip.data[offsetFlip + 1] = imageData.data[offset + 1] ;
        imageFlip.data[offsetFlip + 2] = imageData.data[offset + 2] ;
        imageFlip.data[offsetFlip + 3] = imageData.data[offset + 3] ;
    }

    var canvasFlip = document.createElement('canvas') ;
    canvasFlip.setAttribute('width', width) ;
    canvasFlip.setAttribute('height', height) ;

    canvasFlip.getContext('2d').putImageData(imageFlip, 0, 0) ;
    return canvasFlip ;
}

function flip_index (kPel, width, height) {
    var i     = Math.floor (kPel / width) ;
    var j     = kPel % width ;
    var jFlip = width - j - 1 ;
    var kFlip = i * width + jFlip ;
    return kFlip ;
}

回答by Martijn

For anyone stumbling upon this. If you want to do more complex drawing, the other scale-based answers don't all work. By 'complex' i mean situations where things are more dynamic, like for games.

对于任何绊倒这一点的人。如果您想做更复杂的绘图,其他基于比例的答案并不适用。“复杂”是指事物更具动态性的情况,例如游戏。

The problem being that the location is also flipped. So if you want to draw a small image in the top left corner of the canvas and then flip it horizontally, it will relocate to the top right.

问题是位置也被翻转了。所以如果你想在画布的左上角画一个小图然后水平翻转,它会重新定位到右上角。

The fix is to translate to the center of where you want to draw the image, then scale, then translate back. Like so:

解决方法是平移到要绘制图像的中心,然后缩放,然后平移回来。像这样:

if (flipped) {
  ctx.translate(x + width/2, y + width/2);
  ctx.scale(-1, 1);
  ctx.translate(-(x + width/2), -(y + width/2));
}
ctx.drawImage(img, x, y, width, height);

Here x and y are the location you want to draw the image, and width and height are the width and height you want to draw the image.

这里x和y是你要绘制图像的位置,width和height是你要绘制图像的宽度和高度。