图片分割为九宫格

效果图如上:

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>图片九宫格</title>
    </head>
    <body>
        <h1>点击图片切割</h1>
        <img id="img" style="display: none;" src="imgs/icon.jpeg" />
        <canvas id="imageC" width="900" height="300"></canvas>
        <script type="text/javascript">
            window.onload = function () {
                let canvas = document.getElementById('imageC');
                let ctx = canvas.getContext('2d');
                let img = document.getElementById('img');
                let btn = document.getElementById('btn');
                
                const W = 300
                const H = 300
                
                ctx.drawImage(img, 0, 0, W, H);
                /* 点击裁剪 */
                canvas.onclick = function () {
                    const numX = 3
                    const numY = 3
                    
                    /* 等分图片 */
                    for (let x=0; x<numX; x++) {
                        for (let y=0; y<numY; y++) {
                            /* 切割的宽高 */
                            const copyW = W/numX
                            const copyH = H/numY
                            /* x坐标 */
                            const locx = copyW * x   
                            /* y坐标 */
                            const locY = copyH * y

                            let imgData = ctx.getImageData(locx, locY, copyW, copyH)
                            /* 
                                x          y 时          w/h    位置: 
                                0             0          100    300   0     
                                100           0                 400   0
                                200        0                500   0
                                0          100              300   100
                                100        100              400   100
                                200        100              500   100
                                0          200              300   200
                                100        200              400   200
                                100        200              500   200
                             */
                            const px = 300+ 105*(x+1)
                            const py = 105*y
                            
                            console.log(px, py)
                            ctx.putImageData(imgData, px, py)
                        }
                    }
                }
            }
        </script>
    </body>
</html>

猜你喜欢

转载自www.cnblogs.com/mp1994/p/11133472.html