セレクターと拡大表示用のヘルパー関数を作成する
スクリプトの主な機能は、拡大効果を作成して画像の必要な部分をコピーすることです。これらの機能を定義しましょう。
- 正方形とコピー用のキャンバスを表示または非表示にする関数を定義する。
// 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
);
}