JavaScript - canvas - 放大镜

效果

在这里插入图片描述

示例

项目结构:

在这里插入图片描述

源码:文章来源地址https://uudwc.com/A/0kam5

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>放大镜</title>
        <style type="text/css">
            div {
                width: 200px;
                height: 200px;
                display: inline-block;
            }
        </style>
    </head>
    <body>
        <canvas id="canvas"></canvas>
        <canvas id="piece" width="200" height="200" style="border: 1px solid black;"></canvas>
        
        <script type="text/javascript">
            window.onload = (event) => {
                // console.log(event);
                main();
            }
            
            function main() {
                const canvas = document.querySelector("#canvas");
                const canvasContext = canvas.getContext("2d");
                
                const canvasPiece = document.querySelector("#piece");
                const canvasPieceContext = canvasPiece.getContext("2d");
                // canvasPieceContext.imageSmoothingEnabled = false;
                
                // Load image
                const image = new Image();
                image.onload = (event) => {
                    // console.log(event);
                    canvas.width = image.width;
                    canvas.height = image.height;
                    canvasContext.drawImage(image, 0, 0);
                }
                image.src = "img/transformers.jpg";
                
                // Hovered
                canvas.onmousemove = (event) => {
                    // console.log(event);
                    const x = event.layerX;
                    const y = event.layerY;
                    
                    // 两倍放大
                    {
                        // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
                        // drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
                        // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas#zooming_and_anti-aliasing
                        canvasPieceContext.drawImage(canvas, (x - 50), (y - 50), 100, 100, 0, 0, (100 * 2), (100 * 2));
                    }
                }
            }
        </script>
    </body>
</html>

原文地址:https://blog.csdn.net/qq_29761395/article/details/133170231

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年09月23日 16:50
QT:制作图片浏览器
下一篇 2023年09月23日 16:50