【问题标题】:how to skew image like this如何像这样倾斜图像
【发布时间】:2021-04-01 10:51:04
【问题描述】:

我想像这样倾斜图像,我需要为 context.setTransform 设置哪些参数?

【问题讨论】:

标签: javascript canvas


【解决方案1】:

您无法通过单个 2D 变换来实现这一点。

二维变换允许您通过将第二个参数中倾斜角的切线传递给setTransform() 来“向上”或“向下”倾斜图像,但您希望以对称方式执行这两种操作(导致“近”和/或“远”变形)。你需要一个 3D 变换来做到这一点。

但是,您可以通过将图像分割成几个水平“带”并在渲染每个带时应用不同的变换来模拟相同的结果。距离图像的一半较远的条带将应用更强的倾斜角。比如:

var width = image.width,
    height = image.height,
    context = $("canvas")[0].getContext("2d");
for (var i = 0; i <= height / 2; ++i) {
    context.setTransform(1, -0.4 * i / height, 0, 1, 0, 60);
    context.drawImage(image,
        0, height / 2 - i, width, 2,
        0, height / 2 - i, width, 2);
    context.setTransform(1, 0.4 * i / height, 0, 1, 0, 60);
    context.drawImage(image,
        0, height / 2 + i, width, 2,
        0, height / 2 + i, width, 2);
}

请注意,条带的高度是两个像素而不是一个,以避免出现波纹效应。

你可以在this fiddle看到结果。

【讨论】:

  • 嗨 Frédéric,您能解释一下如何应用转换来获得问题中图像的镜像。即左侧的高度较大,右侧的高度较小。谢谢
  • 不,如果你使用垂直方向的 1 像素宽的带宽,你也可以避免莫尔效应
  • @Eric,你说得对,我对此视而不见,因为我的想法是围绕水平轴进行迭代。围绕垂直轴进行迭代确实可以更有效。谢谢你的评论:)
【解决方案2】:

这是我在玩 JS 渲染伪 3d 透视图时写的一个函数。

与基于条纹的转换函数不同(诚然,对于大多数标准用例来说,它已经足够好了),这个函数使用一个由 4 个角组成的矩阵来定义一个自定义的四边形,原始矩形应该被转换成这个四边形。 这增加了一些灵活性,可用于为“墙上绘画”水平透视和“地板上地毯”垂直透视(以及不对称四边形以获得更多 3d 感觉)渲染自定义梯形)。

function drawImageInPerspective(
        srcImg,
        targetCanvas,
        //Define where on the canvas the image should be drawn:  
        //coordinates of the 4 corners of the quadrilateral that the original rectangular image will be transformed onto:
        topLeftX, topLeftY,
        bottomLeftX, bottomLeftY,
        topRightX, topRightY,
        bottomRightX, bottomRightY,
        //optionally flip the original image horizontally or vertically *before* transforming the original rectangular image to the custom quadrilateral:
        flipHorizontally,
        flipVertically
    ) {

    var srcWidth=srcImg.naturalWidth;
    var srcHeight=srcImg.naturalHeight;

    var targetMarginX=Math.min(topLeftX, bottomLeftX, topRightX, bottomRightX);
    var targetMarginY=Math.min(topLeftY, bottomLeftY, topRightY, bottomRightY);

    var targetTopWidth=(topRightX-topLeftX);
    var targetTopOffset=topLeftX-targetMarginX;
    var targetBottomWidth=(bottomRightX-bottomLeftX);
    var targetBottomOffset=bottomLeftX-targetMarginX;

    var targetLeftHeight=(bottomLeftY-topLeftY);
    var targetLeftOffset=topLeftY-targetMarginY;
    var targetRightHeight=(bottomRightY-topRightY);
    var targetRightOffset=topRightY-targetMarginY;

    var tmpWidth=Math.max(targetTopWidth+targetTopOffset, targetBottomWidth+targetBottomOffset);
    var tmpHeight=Math.max(targetLeftHeight+targetLeftOffset, targetRightHeight+targetRightOffset);

    var tmpCanvas=document.createElement('canvas');
    tmpCanvas.width=tmpWidth;
    tmpCanvas.height=tmpHeight;
    var tmpContext = tmpCanvas.getContext('2d');

    tmpContext.translate(
        flipHorizontally ? tmpWidth : 0,
        flipVertically ? tmpHeight : 0
    );
     tmpContext.scale(
        (flipHorizontally ? -1 : 1)*(tmpWidth/srcWidth),
        (flipVertically? -1 : 1)*(tmpHeight/srcHeight)
    );

    tmpContext.drawImage(srcImg, 0, 0);  

    var tmpMap=tmpContext.getImageData(0,0,tmpWidth,tmpHeight);
    var tmpImgData=tmpMap.data;

    var targetContext=targetCanvas.getContext('2d');
    var targetMap = targetContext.getImageData(targetMarginX,targetMarginY,tmpWidth,tmpHeight);
    var targetImgData = targetMap.data;

    var tmpX,tmpY,
        targetX,targetY,
        tmpPoint, targetPoint;

    for(var tmpY = 0; tmpY < tmpHeight; tmpY++) {
        for(var tmpX = 0;  tmpX < tmpWidth; tmpX++) {

            //Index in the context.getImageData(...).data array.
            //This array is a one-dimensional array which reserves 4 values for each pixel [red,green,blue,alpha) stores all points in a single dimension, pixel after pixel, row after row:
            tmpPoint=(tmpY*tmpWidth+tmpX)*4;

            //calculate the coordinates of the point on the skewed image.
            //
            //Take the X coordinate of the original point and translate it onto target (skewed) coordinate:
            //Calculate how big a % of srcWidth (unskewed x) tmpX is, then get the average this % of (skewed) targetTopWidth and targetBottomWidth, weighting the two using the point's Y coordinate, and taking the skewed offset into consideration (how far topLeft and bottomLeft of the transformation trapezium are from 0).   
            targetX=(
                       targetTopOffset
                       +targetTopWidth * tmpX/tmpWidth
                   )
                   * (1- tmpY/tmpHeight)
                   + (
                       targetBottomOffset
                       +targetBottomWidth * tmpX/tmpWidth
                   )
                   * (tmpY/tmpHeight)
            ;
            targetX=Math.round(targetX);

            //Take the Y coordinate of the original point and translate it onto target (skewed) coordinate:
            targetY=(
                       targetLeftOffset
                       +targetLeftHeight * tmpY/tmpHeight
                   )
                   * (1-tmpX/tmpWidth)
                   + (
                       targetRightOffset
                       +targetRightHeight * tmpY/tmpHeight
                   )
                   * (tmpX/tmpWidth)
            ;
            targetY=Math.round(targetY);

            targetPoint=(targetY*tmpWidth+targetX)*4;

            targetImgData[targetPoint]=tmpImgData[tmpPoint];  //red
            targetImgData[targetPoint+1]=tmpImgData[tmpPoint+1]; //green
            targetImgData[targetPoint+2]=tmpImgData[tmpPoint+2]; //blue
            targetImgData[targetPoint+3]=tmpImgData[tmpPoint+3]; //alpha
        }
    }

    targetContext.putImageData(targetMap,targetMarginX,targetMarginY);
}

这是如何称呼它的:

function onLoad() {
    var canvas = document.createElement("canvas");
    canvas.id = 'canvas';
    canvas.width=800;
    canvas.height=800;
    document.body.appendChild(canvas);

    var img = new Image();
    img.onload = function(){ 
        //draw the original rectangular image as a 300x300 quadrilateral with its bottom-left and top-right corners skewed a bit:
        drawImageInPerspective(
         img, canvas,
         //coordinates of the 4 corners of the quadrilateral that the original rectangular image will be transformed onto:
         0, 0, //top left corner: x, y
         50, 300, //bottom left corner: x, y - position it 50px more to the right than the top right corner
         300, 50, //top right corner: x, y - position it 50px below the top left corner 
         300, 300, //bottom right corner: x,y
         false, //don't flip the original image horizontally
         false //don't flip the original image vertically
        );
    }
    img.src="img/rectangle.png";
}

尽管进行了所有逐像素计算,但它实际上非常高效,并且可以完成工作:

transformed image

...但可能有更优雅的方式来做到这一点。

【讨论】:

    【解决方案3】:

    有一种将矩形转换为梯形的方法,请参阅this stack overflow answer。但是,您需要在每个像素上使用它。

    您还可以将图像切成 1 像素宽的垂直条带,然后从其中心拉伸每个条带。

    假设这会导致 w 个条带,并且您希望梯形的左手边是右手边的 80%

    对于条带 n,拉伸应该是 1+n/(4w)

    【讨论】:

      【解决方案4】:

      这仍然只是未来的,但它太酷了,我已经忍不住要添加它了。

      Chrome 团队正在开发 adding non-affine transforms to the 2D API
      这将为 2D API 添加一些方法,例如 perspective()rotate3d()rotateAxis(),并扩展其他方法以添加 z 轴,以及改进 setTransform()transform() 以最终接受 3D DOM 矩阵。

      这仍然是非常实验性的,可能仍会改变,但您已经可以在打开 chrome://flags/#enable-experimental-web-platform-features 的情况下在 Chrome Canary 中进行尝试。

      if( CanvasRenderingContext2D.prototype.rotate3d ) {
        onload = (evt) => {
          const img = document.getElementById("img");
          const canvas = document.getElementById("canvas");
          const ctx = canvas.getContext("2d");
          ctx.translate(0, canvas.height/2);
          ctx.perspective(705); // yeah, magic numbers...
          ctx.rotate3d(0, (Math.PI/180) * 321, 0); // and more
          ctx.translate(0, -canvas.height/2);
          const ratio = img.naturalHeight / canvas.height;
          ctx.drawImage(img, 0, canvas.height/2 - img.naturalHeight/2);
        };
      }else {
        console.error( "Your browser doesn't support affine transforms yet" );
      }
      body { margin: 0 }
      canvas, img {
        max-height: 100vh; 
      }
      <canvas id="canvas" width="330" height="426"></canvas>
      <img id="img" src="https://upload.wikimedia.org/wikipedia/en/f/f8/Only_By_the_Night_%28Kings_of_Leon_album_-_cover_art%29.jpg">

      在当前的 Chrome Canary 中呈现为

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-17
        • 2013-07-19
        • 1970-01-01
        • 2020-04-12
        • 1970-01-01
        • 2021-03-19
        • 2011-01-22
        相关资源
        最近更新 更多