Implementa el mecanismo de recorte
Requisitos:
- Conocimiento de la API Canvas en JavaScript para dibujo y manipulación de imágenes.
Funcionalidad:
- Agrega una región de recorte en la imagen mostrada y haz que esta región sea arrastrable. Esto le da a los usuarios la flexibilidad de seleccionar el área deseada para recortar.
Agrega los métodos correspondientes en main.js.
-
Crea un método cutImage
El método cutImage se encarga principalmente de dos tareas: una es crear una capa de máscara, y la otra es utilizar la propiedad background de CSS para proporcionar una vista previa en tiempo real de la área de recorte seleccionada.
cutImage: function () {
var t = this;
t.editBox.height = t.imgHeight;
t.editBox.width = t.imgWidth;
t.editBox.style.display = "block";
t.editBox.style.left = t.px;
t.editBox.style.top = t.py;
var cover = t.editBox.getContext("2d");
cover.fillStyle = "rgba(0, 0, 0, 0.5)";
cover.fillRect(0, 0, t.imgWidth, t.imgHeight);
cover.clearRect(t.sx, t.sy, t.sHeight, t.sWidth);
document.getElementById("show_edit").style.background =
"url(" + t.imgUrl + ")" + -t.sx + "px " + -t.sy + "px no-repeat";
document.getElementById("show_edit").style.height = t.sHeight + "px";
document.getElementById("show_edit").style.width = t.sWidth + "px";
},
- Crea un método
drag
drag: function () {
var t = this;
var draging = false;
var startX = 0;
var startY = 0;
document.getElementById("cover_box").onmousemove = function (e) {
var pageX = e.pageX - (t.regional.offsetLeft + this.offsetLeft);
var pageY = e.pageY - (t.regional.offsetTop + this.offsetTop);
if (
pageX > t.sx &&
pageX < t.sx + t.sWidth &&
pageY > t.sy &&
pageY < t.sy + t.sHeight
) {
this.style.cursor = "move";
this.onmousedown = function () {
draging = true;
t.ex = t.sx;
t.ey = t.sy;
startX = e.pageX - (t.regional.offsetLeft + this.offsetLeft);
startY = e.pageY - (t.regional.offsetTop + this.offsetTop);
};
window.onmouseup = function () {
draging = false;
};
if (draging) {
if (t.ex + (pageX - startX) < 0) {
t.sx = 0;
} else if (t.ex + (pageX - startX) + t.sWidth > t.imgWidth) {
t.sx = t.imgWidth - t.sWidth;
} else {
t.sx = t.ex + (pageX - startX);
}
if (t.ey + (pageY - startY) < 0) {
t.sy = 0;
} else if (t.ey + (pageY - startY) + t.sHeight > t.imgHeight) {
t.sy = t.imgHeight - t.sHeight;
} else {
t.sy = t.ey + (pageY - startY);
}
t.cutImage();
}
} else {
this.style.cursor = "auto";
}
};
},
Para entender este método, debes comprender los siguientes puntos clave:
var pageX = e.pageX - (t.regional.offsetLeft + this.offsetLeft);
var pageY = e.pageY - (t.regional.offsetTop + this.offsetTop);
Con las dos líneas de código anteriores, obtenemos la distancia entre el mouse y la imagen de fondo. e.pageX representa la distancia desde el mouse hasta el borde izquierdo del navegador, y t.regional.offsetLeft + this.offsetLeft calcula la distancia desde la imagen hasta el borde izquierdo del navegador. Del mismo modo, se puede deducir la distancia superior.
if ( pageX > t.sx && pageX < t.sx + t.sWidth && pageY > t.sy && pageY < t.sy + t.sHeight )
Una vez que se ha comprendido la distancia entre el mouse y la imagen de fondo, esto debería ser fácil de entender: determina si el mouse está dentro de la región de la imagen.
t.ex = t.sx;
t.ey = t.sy;
startX = e.pageX - (t.regional.offsetLeft + this.offsetLeft);
startY = e.pageY - (t.regional.offsetTop + this.offsetTop);
Estos dos trozos de código merecen ser resaltados. Las dos primeras líneas registran las coordenadas de la última captura de pantalla (o si no hubo una anterior, entonces las coordenadas iniciales); las dos siguientes líneas registran las coordenadas cuando se presiona el mouse. Puedes inspeccionar estos valores por separado utilizando console.log().
if (draging) {
if (t.ex + (pageX - startX) < 0) {
t.sx = 0;
} else if (t.ex + (pageX - startX) + t.sWidth > t.imgWidth) {
t.sx = t.imgWidth - t.sWidth;
} else {
t.sx = t.ex + (pageX - startX);
}
if (t.ey + (pageY - startY) < 0) {
t.sy = 0;
} else if (t.ey + (pageY - startY) + t.sHeight > t.imgHeight) {
t.sy = t.imgHeight - t.sHeight;
} else {
t.sy = t.ey + (pageY - startY);
}
t.cutImage();
}
El código anterior básicamente dice: si estamos en medio de arrastrar, necesitamos actualizar los valores de t.sx y t.sy en tiempo real según los cambios de coordenadas y llamar al método cutImage para proporcionar una vista previa en vivo.
Las coordenadas de la área de recorte durante el movimiento = última posición registrada + (posición actual del mouse - posición cuando se presionó el mouse)