JavaScript - canvas - 放大镜

效果

示例

项目结构:

源码:

html 复制代码
<!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>
相关推荐
cs_dn_Jie1 小时前
钉钉 H5 微应用 手机端调试
前端·javascript·vue.js·vue·钉钉
开心工作室_kaic2 小时前
ssm068海鲜自助餐厅系统+vue(论文+源码)_kaic
前端·javascript·vue.js
有梦想的刺儿2 小时前
webWorker基本用法
前端·javascript·vue.js
清灵xmf3 小时前
TypeScript 类型进阶指南
javascript·typescript·泛型·t·infer
小白学大数据3 小时前
JavaScript重定向对网络爬虫的影响及处理
开发语言·javascript·数据库·爬虫
qq_390161773 小时前
防抖函数--应用场景及示例
前端·javascript
334554324 小时前
element动态表头合并表格
开发语言·javascript·ecmascript
John.liu_Test4 小时前
js下载excel示例demo
前端·javascript·excel
PleaSure乐事4 小时前
【React.js】AntDesignPro左侧菜单栏栏目名称不显示的解决方案
前端·javascript·react.js·前端框架·webstorm·antdesignpro
哟哟耶耶4 小时前
js-将JavaScript对象或值转换为JSON字符串 JSON.stringify(this.SelectDataListCourse)
前端·javascript·json