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>
相关推荐
kyriewen2 小时前
我让用户白等两秒,只为一个 16MB 的中文字体
前端·javascript·程序员
泯泷5 小时前
第二章:你的第一个Lit组件 - 从零到"Hello, World"
前端·javascript·web components
多加点辣也没关系6 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
泯泷6 小时前
第三章:lit-html的威力 - 精通声明式模板
前端·javascript·web components
bai2737 小时前
npm 在 cmd 里能跑,Node 的 spawn 一调就 EINVAL:Windows 上 .cmd 的六种调法实测
javascript·后端
晓得迷路了8 小时前
栗子前端技术周刊第 155 期 - 2026 HTML 现状调查报告、Solid 2.0...
前端·javascript·webpack
inksci1 天前
用飞帆做了个小网页
前端·javascript·css·html
zhensherlock1 天前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
多加点辣也没关系1 天前
JavaScript|第40章:JavaScript 工程化实践
开发语言·javascript·ecmascript
彩虹暴龙兽1 天前
JavaScript 预编译机制与执行上下文构建分析
javascript