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