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");
                
                // 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/getImageData
                        const imageData = canvasContext.getImageData((x - 100), (y - 100), 200, 200);
                        console.log(imageData);
                        // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData
                        canvasPieceContext.putImageData(imageData, 0, 0);
                    }
                }
            }
        </script>
    </body>
</html>
相关推荐
web打印社区4 小时前
网页静默打印热敏小票:从 HTML 到出纸的完整指南
前端·javascript·vue.js·electron·pdf·html
专业抄代码选手11 小时前
08|Fiber 上的 `useState`:状态终于属于具体组件
前端·javascript·react.js
默_笙11 小时前
😭 Vibe Coding 翻车实录:AI 编程为什么必须先写"剧本"
前端·javascript
lerhxx12 小时前
我用 R3F 手搓了一个能走进去的 3D 迷宫简历(上):从选型架构到迷宫生成算法
前端·javascript·three.js
鹏多多17 小时前
PC 网站接入微信登录,这 10 个坑我替你踩完了!
前端·javascript·vue.js
用户2986985301418 小时前
React 中 HTML 内容转 Word 文档的实现方案
javascript·react.js·html
mONESY18 小时前
我用 Next.js 16 + Supabase 从零做了个「背单词」H5 应用
javascript
boooooooom18 小时前
手把手做一个图 RAG 烹饪问答系统:Neo4j + Milvus + LLM 的工程实践
前端·javascript·后端
染指111021 小时前
103.RAG-LLamaIndex后端rag问答-聊天接口
前端·javascript·vue.js·人工智能
单线程_011 天前
从案例分析 Vue3 Tokenizer+Parser 源码三
前端·javascript·vue.js