繁体   English   中英

如何使用画布绘制梯形图像

[英]How to draw an image in trapezium shape using canvas

我想使用画布绘制梯形图像。

我尝试了转换,但没有得到梯形视图。

请任何人给我解决方案,以使用画布在梯形视图中绘制图像。

我希望实际图像应该像这样/ _ \\

这是将图像“变换”为梯形的方法。 该技术是众所周知的,将图像线切成线,然后一点一点地按比例绘制线。

此功能允许您设置梯形形状的数量(%)并处理缩放的图像:

function drawTrapezoid(ctx, img, x, y, w, h, factor) {

    var startPoint = x + w * 0.5 * (factor*0.01), // calculate top x
        xi, yi, scale = img.height / h,           // used for interpolation/scale
        startLine = y,                            // used for interpolation
        endLine = y + h;                          // abs. end line (y)

    for(; y < endLine; y++) {

        // get x position based on line (y)
        xi = interpolate(startPoint, y, x, endLine, (y - startLine) / h);

        // get scaled y position for source image
        yi = (y * scale + 0.5)|0;

        // draw the slice
        ctx.drawImage(img, 0, yi, img.width, 1,       // source line
                           xi.x, y, w - xi.x * 2, 1); // output line
    }

    // sub-function doing the interpolation        
    function interpolate(x1, y1, x2, y2, t) {
        return {
            x: x1 + (x2 - x1) * t,
            y: y1 + (y2 - y1) * t
        };
    }
}

小提琴

快照

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM