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>
相关推荐
张元清1 天前
React useDebounce Hook:给状态和回调做防抖(2026)
javascript·react.js
Cobyte1 天前
21.Vue Vapor 组件的实现原理
前端·javascript·vue.js
铁皮饭盒1 天前
Rust版Bun1.4之前, 盘点Bun1.3新特性
前端·javascript·后端
晓得迷路了1 天前
栗子前端技术周刊第 135 期 - Vite 8.1、Rspack 2.1、Babel 8.0...
前端·javascript·vite
To_OC1 天前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC1 天前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
天渺工作室1 天前
实现一个adblock/adblock plus等浏览器广告拦截器检测插件
前端·javascript
kyriewen2 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
minglie2 天前
一个置换问题
javascript
默_笙2 天前
🌀 别再手动写 Prompt 了!我让 AI 自己循环改到满意为止
javascript