效果
示例
项目结构:
源码:
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>