Use canvas to achieve flip the picture

To achieve through the canvas of pictures along the x-axis or y-axis to achieve color flip, we can achieve by canvas2d interface.

To use the api:
Use getContext to get canvas2d objects
scale method canvas2d object is flipped
due to the reversal of the xy axis using the origin, which is the axis position of the upper left corner of the canvas, therefore, we also need to translate method, to move the picture to move the reversed display area of the canvas

Having logic, then click on the flip short codes:

  1. Along the x-axis inverted codes:
        //垂直翻转
        ctx.scale(1, -1);
        ctx.translate(0, -canvas.height);
  1. The y-axis inverted codes:
        //水平翻转
        ctx.scale(-1, 1);
        ctx.translate(-canvas.width, 0);

These are along the x-axis and y-axis inverted code, the following code is then enclose a demo of:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
</body>
<script>
    var preName = './textures/build/admin_edit/1574131406/a1574212341_p0_';
    var img = new Image();
    img.src = preName+ 'x.jpg';
    img.onload = function () {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.height = img.height;
        canvas.width = img.width;
        //水平翻转
        ctx.scale(-1, 1);
        ctx.translate(-img.width, 0);
        //垂直翻转
        ctx.scale(1, -1);
        ctx.translate(0, -img.height);
        ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
        canvas.style.cssText = 'position:fixed; left:0; top:0;';
        document.body.appendChild(canvas);
    }
</script>
</html>
Published 402 original articles · won praise 544 · Views 2.12 million +

Guess you like

Origin blog.csdn.net/qq_30100043/article/details/103484616