为选择器和放大显示创建辅助函数
我们脚本的主要功能包括创建放大效果并复制图像的必要部分。现在让我们定义这些功能。
- 定义显示或隐藏方形和复制画布的函数。
// main.js
function showSquare() {
square.style.display = "block";
}
function hideSquare() {
square.style.display = "none";
}
function showCanvas() {
copycanvas.style.display = "inline";
}
function hideCanvas() {
copycanvas.style.display = "none";
}
- 创建放大效果。
function createSquare(x, y) {
// 位置调整,以使方形保持在画布边界内
x = x - 45 < canvas.offsetLeft ? canvas.offsetLeft : x - 45;
y = y - 45 < canvas.offsetTop ? canvas.offsetTop : y - 45;
x = x + 90 < box.right ? x : box.right - 90;
y = y + 90 < box.bottom ? y : box.bottom - 90;
squaredata.left = x; // 更新全局状态
squaredata.top = y;
moveSquare(x, y); // 定位方形
copy(); // 调用放大效果
}
- 定位方形并调用放大功能。
// 移动方形选择器和放大显示的函数
function moveSquare(x, y) {
square.style.left = x + "px";
square.style.top = y + "px";
showCanvas();
showSquare();
}
- 在复制画布上创建放大效果。
function copy() {
copycontext.drawImage(
canvas, // 指定源画布
squaredata.left - box.left, // 开始复制的位置
squaredata.top - box.top,
90, // 要复制的数据的宽度和高度
90,
0, // 复制画布上的目标位置
0,
copycanvas.width,
copycanvas.height
);
}