const inp = document.querySelector(".box .inp"); const cvs = document.querySelector(".box .canvas"); const ctx = cvs.getContext("2d"); const newCvs = document.createElement("canvas"); const newCtx = newCvs.getContext("2d"); const img = new Image();
let initPos = [];
let newCanvas = [];
const init = () => { bindEvent(); };
const bindEvent = () => { inp.addEventListener("change", handleFileSelect, false); cvs.addEventListener("mousedown", handleCvsMousedown, false); };
const handleFileSelect = (e) => { const file = e.target.files[0]; const reader = new FileReader(); reader.onload = function (e) { img.src = e.target.result; img.onload = function () { initCvs(); drawMask(0, 0, cvs.width, cvs.height, 0.5); if (newCanvas.length) { document.body.removeChild(newCvs); } }; }; reader.readAsDataURL(file); };
const initCvs = () => { cvs.width = 700; cvs.height = 700; cvs.style.display = "block"; ctx.drawImage(img, 0, 0, cvs.width, cvs.height); };
const drawMask = (x, y, wid, hei, opacity) => { ctx.fillStyle = `rgba(0,0,0,${opacity})`; ctx.fillRect(x, y, wid, hei); };
const handleCvsMousedown = (e) => { initPos = [e.offsetX, e.offsetY]; cvs.addEventListener("mousemove", handleCvsMousemove, false); cvs.addEventListener("mouseup", handleCvsMouseup, false); cvs.addEventListener("mouseleave", handleCvsMouseup, false); cvs.addEventListener("mouseenter", handleCvsMouseup, false); };
const handleCvsMousemove = (e) => { const { offsetX: endX, offsetY: endY } = e; const [startX, startY] = initPos; const wid = endX - startX; const hei = endY - startY; newCanvas = [startX, startY, wid, hei]; ctx.clearRect(0, 0, cvs.width, cvs.height); drawMask(0, 0, cvs.width, cvs.height, 0.5); drawSelect(cvs.width, cvs.height, wid, hei); };
const drawSelect = (cvsWid, cvsHei, wid, hei) => { ctx.globalCompositeOperation = "destination-out"; ctx.fillStyle = "rgba(0,0,0,1)"; ctx.fillRect(...initPos, wid, hei); ctx.globalCompositeOperation = "destination-over"; ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, cvsWid, cvsHei); };
const handleCvsMouseup = (e) => { cvs.removeEventListener("mousemove", handleCvsMousemove, false); cvs.removeEventListener("mouseup", handleCvsMouseup, false); cvs.removeEventListener("mouseleave", handleCvsMouseup, false); cvs.removeEventListener("mouseenter", handleCvsMouseup, false); drawNewCvs(newCanvas); };
const drawNewCvs = (newCanvas) => { const data = ctx.getImageData(...newCanvas); newCtx.clearRect(...newCanvas); newCvs.width = newCanvas[2]; newCvs.height = newCanvas[3]; newCtx.putImageData(data, 0, 0); document.body.appendChild(newCvs); }; init();
|