mjon_git/src/main/webapp/js/service-basic.js
2023-06-12 11:15:02 +09:00

1460 lines
41 KiB
JavaScript

/* service-basic.js
* @author NHN. FE Development Team <dl_javascript@nhn.com>
* @fileoverview
*/
/* eslint-disable vars-on-top,no-var,strict,prefer-template,prefer-arrow-callback,prefer-destructuring,object-shorthand,require-jsdoc,complexity,prefer-const,no-unused-vars */
var PIXELATE_FILTER_DEFAULT_VALUE = 20;
var supportingFileAPI = !!(window.File && window.FileList && window.FileReader);
var rImageType = /data:(image\/.+);base64,/;
var shapeOptions = {};
var shapeType;
var activeObjectId;
var activeCropEnter = false;
// Buttons
var $btns = $('.menu-item');
var $btnsActivatable = $btns.filter('.activatable');
var $inputImage = $('.input-image-file');
var $btnDownload = $('#btn-download');
var $btnUndo = $('#btn-undo');
var $btnRedo = $('#btn-redo');
var $btnClearObjects = $('#btn-clear-objects');
var $btnReset = $('#btn-reset');
var $btnRemoveActiveObject = $('#btn-remove-active-object');
var $btnCrop = $('#btn-crop');
var $btnFlip = $('#btn-flip');
var $btnRotation = $('#btn-rotation');
var $btnDrawLine = $('#btn-draw-line');
var $btnDrawShape = $('#btn-draw-shape');
var $btnApplyCrop = $('#btn-apply-crop');
var $btnCancelCrop = $('#btn-cancel-crop');
var $btnFlipX = $('#btn-flip-x');
var $btnFlipY = $('#btn-flip-y');
var $btnResetFlip = $('#btn-reset-flip');
var $btnRotateClockwise = $('#btn-rotate-clockwise');
var $btnRotateCounterClockWise = $('#btn-rotate-counter-clockwise');
var $btnText = $('#btn-text');
var $btnTextStyle = $('.btn-text-style');
var $btnTextFamily = $('.btn-text-family');
var $btnAddIcon = $('#btn-add-icon');
var $btnRegisterIcon = $('#btn-register-icon');
var $btnMaskFilter = $('#btn-mask-filter');
var $btnImageFilter = $('#btn-image-filter');
var $btnLoadMaskImage = $('#input-mask-image-file');
var $btnApplyMask = $('#btn-apply-mask');
var $btnClose = $('.close');
// Input etc.
var $inputRotationRange = $('#input-rotation-range');
var $inputBrushWidthRange = $('#input-brush-width-range');
var $inputFontSizeRange = $('#input-font-size-range');
var $inputFontSizeList = $('#font_size_list');
var $inputStrokeWidthRange = $('#input-stroke-width-range');
var $inputCheckTransparent = $('#input-check-transparent');
var $inputCheckFilter = $('#input-check-filter');
var $inputCheckGrayscale = $('#input-check-grayscale');
var $inputCheckInvert = $('#input-check-invert');
var $inputCheckSepia = $('#input-check-sepia');
var $inputCheckSepia2 = $('#input-check-sepia2');
var $inputCheckBlur = $('#input-check-blur');
var $inputCheckSharpen = $('#input-check-sharpen');
var $inputCheckEmboss = $('#input-check-emboss');
var $inputCheckRemoveWhite = $('#input-check-remove-white');
var $inputRangeRemoveWhiteThreshold = $('#input-range-remove-white-threshold');
var $inputRangeRemoveWhiteDistance = $('#input-range-remove-white-distance');
var $inputCheckBrightness = $('#input-check-brightness');
var $inputRangeBrightnessValue = $('#input-range-brightness-value');
var $inputCheckNoise = $('#input-check-noise');
var $inputRangeNoiseValue = $('#input-range-noise-value');
var $inputCheckPixelate = $('#input-check-pixelate');
var $inputRangePixelateValue = $('#input-range-pixelate-value');
var $inputCheckTint = $('#input-check-tint');
var $inputRangeTintOpacityValue = $('#input-range-tint-opacity-value');
var $inputCheckMultiply = $('#input-check-multiply');
var $inputCheckBlend = $('#input-check-blend');
var $inputCheckColorFilter = $('#input-check-color-filter');
var $inputRangeColorFilterValue = $('#input-range-color-filter-value');
// Sub menus
var $displayingSubMenu = $();
var $cropSubMenu = $('#crop-sub-menu');
var $flipSubMenu = $('#flip-sub-menu');
var $rotationSubMenu = $('#rotation-sub-menu');
var $freeDrawingSubMenu = $('#free-drawing-sub-menu');
var $drawLineSubMenu = $('#draw-line-sub-menu');
var $drawShapeSubMenu = $('#draw-shape-sub-menu');
var $textSubMenu = $('#text-sub-menu');
var $iconSubMenu = $('#icon-sub-menu');
var $filterSubMenu = $('#filter-sub-menu');
var $imageFilterSubMenu = $('#image-filter-sub-menu');
// Select line type
var $selectLine = $('[name="select-line-type"]');
// Select shape type
var $selectShapeType = $('[name="select-shape-type"]');
// Select color of shape type
var $selectColorType = $('[name="select-color-type"]');
// Select blend type
var $selectBlendType = $('[name="select-blend-type"]');
var editorNumber = "1";
// Image editor
var imageEditor1 = new tui.ImageEditor('#tui-image-editor1', {
cssMaxWidth: 500,
cssMaxHeight: 750,
selectionStyle: {
cornerSize: 20,
rotatingPointOffset: 70,
},
});
var imageEditor2 = new tui.ImageEditor('#tui-image-editor2', {
cssMaxWidth: 500,
cssMaxHeight: 750,
selectionStyle: {
cornerSize: 20,
rotatingPointOffset: 70,
},
});
var imageEditor3 = new tui.ImageEditor('#tui-image-editor3', {
cssMaxWidth: 500,
cssMaxHeight: 750,
selectionStyle: {
cornerSize: 20,
rotatingPointOffset: 70,
},
});
// Color picker for text palette
var textColorpicker = tui.colorPicker.create({
container: $('#tui-text-color-picker')[0],
color: '#000000',
});
// Common global functions
// HEX to RGBA
function hexToRGBa(hex, alpha) {
var r = parseInt(hex.slice(1, 3), 16);
var g = parseInt(hex.slice(3, 5), 16);
var b = parseInt(hex.slice(5, 7), 16);
var a = alpha || 1;
return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
}
function base64ToBlob(data) {
var mimeString = '';
var raw, uInt8Array, i, rawLength;
raw = data.replace(rImageType, function (header, imageType) {
mimeString = imageType;
return '';
});
raw = atob(raw);
rawLength = raw.length;
uInt8Array = new Uint8Array(rawLength); // eslint-disable-line
for (i = 0; i < rawLength; i += 1) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: mimeString });
}
function resizeEditor() {
//var $editor = $('.tui-image-editor');
//var $container = $('.tui-image-editor-canvas-container');
var $editor = $("#tui-image-editor" + editorNumber);
var $container = $($("#tui-image-editor" + editorNumber + " > .tui-image-editor-canvas-container"));
var height = parseFloat($container.css('max-height'));
$editor.height(height);
}
function canvasTab(num) {
// 다른 캔버스를 선택하려 할 때 크롭모드를 끝내고 크롭을 적용시켜주기 버튼
if(activeCropEnter == true) {
activeCropEnter = false;
$btnApplyCrop.trigger("click");
}
editorNumber = num;
if(num == "1") {
$("#tui-image-editor1").show();
$("#tui-image-editor2").hide();
$("#tui-image-editor3").hide();
}
if(num == "2") {
$("#tui-image-editor1").hide();
$("#tui-image-editor2").show();
$("#tui-image-editor3").hide();
}
if(num == "3") {
$("#tui-image-editor1").hide();
$("#tui-image-editor2").hide();
$("#tui-image-editor3").show();
}
$("#preview"+num).addClass("on");
$("#preview"+num).siblings(".preview").removeClass("on");
$(".imageSize").hide();
$("#imageSize"+num).show();
if(window['imageEditor'+editorNumber].getImageName()=='SampleImage' || window['imageEditor'+editorNumber].getImageName()=='') {
tabDisable();
} else {
tabActive();
}
}
function getBrushSettings() {
var brushWidth = parseInt($inputBrushWidthRange.val(), 10);
var brushColor = brushColorpicker.getColor();
return {
width: brushWidth,
color: hexToRGBa(brushColor, 0.5),
};
}
function activateShapeMode() {
if (window['imageEditor'+editorNumber].getDrawingMode() !== 'SHAPE') {
window['imageEditor'+editorNumber].stopDrawingMode();
window['imageEditor'+editorNumber].startDrawingMode('SHAPE');
}
}
function activateIconMode() {
window['imageEditor'+editorNumber].stopDrawingMode();
}
function activateTextMode() {
if (window['imageEditor'+editorNumber].getDrawingMode() !== 'TEXT') {
window['imageEditor'+editorNumber].stopDrawingMode();
window['imageEditor'+editorNumber].startDrawingMode('TEXT');
}
}
function setTextToolbar(obj) {
var fontSize = obj.fontSize;
var fontColor = obj.fill;
$inputFontSizeRange.val(fontSize);
textColorpicker.setColor(fontColor);
}
function setIconToolbar(obj) {
var iconColor = obj.fill;
//iconColorpicker.setColor(iconColor);
}
function setShapeToolbar(obj) {
var fillColor, isTransparent, isFilter;
var colorType = $selectColorType.val();
var changeValue = colorType === 'stroke' ? obj.stroke : obj.fill.type;
isTransparent = changeValue === 'transparent';
isFilter = changeValue === 'filter';
if (colorType === 'stroke') {
if (!isTransparent && !isFilter) {
shapeColorpicker.setColor(changeValue);
}
} else if (colorType === 'fill') {
if (!isTransparent && !isFilter) {
fillColor = obj.fill.color;
shapeColorpicker.setColor(fillColor);
}
}
$inputCheckTransparent.prop('checked', isTransparent);
$inputCheckFilter.prop('checked', isFilter);
$inputStrokeWidthRange.val(obj.strokeWidth);
}
function showSubMenu(type) {
var $submenu;
switch (type) {
case 'shape':
$submenu = $drawShapeSubMenu;
break;
case 'icon':
$submenu = $iconSubMenu;
break;
case 'text':
$submenu = $textSubMenu;
break;
default:
$submenu = 0;
}
//$displayingSubMenu.hide();
//$displayingSubMenu = $submenu.show();
}
function applyOrRemoveFilter(applying, type, options) {
if (applying) {
window['imageEditor'+editorNumber].applyFilter(type, options).then(function (result) {
console.log(result);
});
} else {
window['imageEditor'+editorNumber].removeFilter(type);
}
}
// Attach image editor custom events1
imageEditor1.on({
objectAdded: function (objectProps) {
console.info(objectProps);
},
undoStackChanged: function (length) {
if (length) {
$btnUndo.removeClass('disabled');
} else {
$btnUndo.addClass('disabled');
}
resizeEditor();
},
redoStackChanged: function (length) {
if (length) {
$btnRedo.removeClass('disabled');
} else {
$btnRedo.addClass('disabled');
}
resizeEditor();
},
objectScaled: function (obj) {
if (obj.type === 'text') {
$inputFontSizeRange.val(obj.fontSize);
}
},
addText: function (pos) {
imageEditor1
.addText('텍스트를 입력하세요', {
position: pos.originPosition,
})
.then(function (objectProps) {
console.log(objectProps);
});
},
objectActivated: function (obj) {
activeObjectId = obj.id;
if (obj.type === 'rect' || obj.type === 'circle' || obj.type === 'triangle') {
showSubMenu('shape');
setShapeToolbar(obj);
activateShapeMode();
} else if (obj.type === 'icon') {
showSubMenu('icon');
setIconToolbar(obj);
activateIconMode();
} else if (obj.type === 'text') {
showSubMenu('text');
setTextToolbar(obj);
activateTextMode();
}
},
mousedown: function (event, originPointer) {
if ($imageFilterSubMenu.is(':visible') && imageEditor1.hasFilter('colorFilter')) {
imageEditor1.applyFilter('colorFilter', {
x: parseInt(originPointer.x, 10),
y: parseInt(originPointer.y, 10),
});
}
},
});
// Attach image editor custom events
imageEditor2.on({
objectAdded: function (objectProps) {
console.info(objectProps);
},
undoStackChanged: function (length) {
if (length) {
$btnUndo.removeClass('disabled');
} else {
$btnUndo.addClass('disabled');
}
resizeEditor();
},
redoStackChanged: function (length) {
if (length) {
$btnRedo.removeClass('disabled');
} else {
$btnRedo.addClass('disabled');
}
resizeEditor();
},
objectScaled: function (obj) {
if (obj.type === 'text') {
$inputFontSizeRange.val(obj.fontSize);
}
},
addText: function (pos) {
imageEditor2
.addText('텍스트를 입력하세요', {
position: pos.originPosition,
})
.then(function (objectProps) {
console.log(objectProps);
});
},
objectActivated: function (obj) {
activeObjectId = obj.id;
if (obj.type === 'rect' || obj.type === 'circle' || obj.type === 'triangle') {
showSubMenu('shape');
setShapeToolbar(obj);
activateShapeMode();
} else if (obj.type === 'icon') {
showSubMenu('icon');
setIconToolbar(obj);
activateIconMode();
} else if (obj.type === 'text') {
showSubMenu('text');
setTextToolbar(obj);
activateTextMode();
}
},
mousedown: function (event, originPointer) {
if ($imageFilterSubMenu.is(':visible') && imageEditor2.hasFilter('colorFilter')) {
imageEditor2.applyFilter('colorFilter', {
x: parseInt(originPointer.x, 10),
y: parseInt(originPointer.y, 10),
});
}
},
});
// Attach image editor custom events
imageEditor3.on({
objectAdded: function (objectProps) {
console.info(objectProps);
},
undoStackChanged: function (length) {
if (length) {
$btnUndo.removeClass('disabled');
} else {
$btnUndo.addClass('disabled');
}
resizeEditor();
},
redoStackChanged: function (length) {
if (length) {
$btnRedo.removeClass('disabled');
} else {
$btnRedo.addClass('disabled');
}
resizeEditor();
},
objectScaled: function (obj) {
if (obj.type === 'text') {
$inputFontSizeRange.val(obj.fontSize);
}
},
addText: function (pos) {
imageEditor3
.addText('텍스트를 입력하세요', {
position: pos.originPosition,
})
.then(function (objectProps) {
console.log(objectProps);
});
},
objectActivated: function (obj) {
activeObjectId = obj.id;
if (obj.type === 'rect' || obj.type === 'circle' || obj.type === 'triangle') {
showSubMenu('shape');
setShapeToolbar(obj);
activateShapeMode();
} else if (obj.type === 'icon') {
showSubMenu('icon');
setIconToolbar(obj);
activateIconMode();
} else if (obj.type === 'text') {
showSubMenu('text');
setTextToolbar(obj);
activateTextMode();
}
},
mousedown: function (event, originPointer) {
if ($imageFilterSubMenu.is(':visible') && imageEditor3.hasFilter('colorFilter')) {
imageEditor3.applyFilter('colorFilter', {
x: parseInt(originPointer.x, 10),
y: parseInt(originPointer.y, 10),
});
}
},
});
// Attach button click event listeners
$btns.on('click', function () {
$btnsActivatable.removeClass('active');
});
$btnsActivatable.on('click', function () {
$(this).addClass('active');
});
$btnUndo.on('click', function () {
$displayingSubMenu.hide();
if (!$(this).hasClass('disabled')) {
window['imageEditor'+editorNumber].discardSelection();
window['imageEditor'+editorNumber].undo();
}
});
$btnRedo.on('click', function () {
$displayingSubMenu.hide();
if (!$(this).hasClass('disabled')) {
window['imageEditor'+editorNumber].discardSelection();
window['imageEditor'+editorNumber].redo();
}
});
$btnClearObjects.on('click', function () {
$displayingSubMenu.hide();
window['imageEditor'+editorNumber].clearObjects();
});
$btnReset.on('click', function () {
window['imageEditor'+editorNumber].undo(999);
});
$btnRemoveActiveObject.on('click', function () {
$displayingSubMenu.hide();
window['imageEditor'+editorNumber].removeObject(activeObjectId);
});
$btnCrop.on('click', function () {
window['imageEditor'+editorNumber].startDrawingMode('CROPPER');
$displayingSubMenu.hide();
$displayingSubMenu = $cropSubMenu.show();
activeCropEnter = true;
});
$btnFlip.on('click', function () {
window['imageEditor'+editorNumber].stopDrawingMode();
$displayingSubMenu.hide();
$displayingSubMenu = $flipSubMenu.show();
});
$(window).keydown(function(keyNum){
if(keyNum.keyCode == 13 && activeCropEnter == true){
activeCropEnter = false;
$btnApplyCrop.trigger("click");
}
})
$btnRotation.on('click', function () {
window['imageEditor'+editorNumber].stopDrawingMode();
$displayingSubMenu.hide();
$displayingSubMenu = $rotationSubMenu.show();
});
$btnClose.on('click', function () {
window['imageEditor'+editorNumber].stopDrawingMode();
$displayingSubMenu.hide();
});
$btnApplyCrop.on('click', function () {
window['imageEditor'+editorNumber].crop(window['imageEditor'+editorNumber].getCropzoneRect()).then(function () {
window['imageEditor'+editorNumber].stopDrawingMode();
$cropSubMenu.hide();
resizeEditor();
});
});
$btnCancelCrop.on('click', function () {
window['imageEditor'+editorNumber].stopDrawingMode();
$cropSubMenu.hide();
});
$btnFlipX.on('click', function () {
window['imageEditor'+editorNumber].flipX().then(function (status) {
console.log('flipX: ', status.flipX);
console.log('flipY: ', status.flipY);
console.log('angle: ', status.angle);
});
});
$btnFlipY.on('click', function () {
window['imageEditor'+editorNumber].flipY().then(function (status) {
console.log('flipX: ', status.flipX);
console.log('flipY: ', status.flipY);
console.log('angle: ', status.angle);
});
});
$btnResetFlip.on('click', function () {
window['imageEditor'+editorNumber].resetFlip().then(function (status) {
console.log('flipX: ', status.flipX);
console.log('flipY: ', status.flipY);
console.log('angle: ', status.angle);
});
});
$btnRotateClockwise.on('click', function () {
window['imageEditor'+editorNumber].rotate(90);
});
$btnRotateCounterClockWise.on('click', function () {
window['imageEditor'+editorNumber].rotate(-90);
});
$inputRotationRange.on('mousedown', function () {
var changeAngle = function () {
window['imageEditor'+editorNumber].setAngle(parseInt($inputRotationRange.val(), 10))['catch'](function () {});
};
$(document).on('mousemove', changeAngle);
$(document).on('mouseup', function stopChangingAngle() {
$(document).off('mousemove', changeAngle);
$(document).off('mouseup', stopChangingAngle);
});
});
$inputRotationRange.on('change', function () {
window['imageEditor'+editorNumber].setAngle(parseInt($inputRotationRange.val(), 10))['catch'](function () {});
});
$inputBrushWidthRange.on('change', function () {
window['imageEditor'+editorNumber].setBrush({ width: parseInt(this.value, 10) });
});
$inputImage.on('change', function (event) {
var files;
if (!supportingFileAPI) {
alert('This browser does not support file-api');
}
files = event.target.files;
selectFile(files);
});
$btnDownload.on('click', function () {
var imageName = window['imageEditor'+editorNumber].getImageName();
var dataURL = window['imageEditor'+editorNumber].toDataURL();
var blob, type, w;
if (supportingFileAPI) {
blob = base64ToBlob(dataURL);
type = blob.type.split('/')[1];
if (imageName.split('.').pop() !== type) {
imageName += '.' + type;
}
// Library: FileSaver - saveAs
saveAs(blob, imageName); // eslint-disable-line
} else {
alert('This browser needs a file-server');
w = window.open();
w.document.body.innerHTML = '<img src="' + dataURL + '">';
}
});
// control draw line mode
$btnDrawLine.on('click', function () {
window['imageEditor'+editorNumber].stopDrawingMode();
$displayingSubMenu.hide();
$displayingSubMenu = $drawLineSubMenu.show();
$selectLine.eq(0).change();
});
$selectLine.on('change', function () {
var mode = $(this).val();
var settings = getBrushSettings();
window['imageEditor'+editorNumber].stopDrawingMode();
if (mode === 'freeDrawing') {
window['imageEditor'+editorNumber].startDrawingMode('FREE_DRAWING', settings);
} else {
window['imageEditor'+editorNumber].startDrawingMode('LINE_DRAWING', settings);
}
});
// control draw shape mode
$btnDrawShape.on('click', function () {
showSubMenu('shape');
// step 1. get options to draw shape from toolbar
shapeType = $('[name="select-shape-type"]:checked').val();
shapeOptions.stroke = '#000000';
shapeOptions.fill = '#ffffff';
shapeOptions.strokeWidth = Number($inputStrokeWidthRange.val());
// step 2. set options to draw shape
window['imageEditor'+editorNumber].setDrawingShape(shapeType, shapeOptions);
// step 3. start drawing shape mode
activateShapeMode();
});
$selectShapeType.on('change', function () {
shapeType = $(this).val();
window['imageEditor'+editorNumber].setDrawingShape(shapeType);
});
$selectColorType.on('change', function () {
var colorType = $(this).val();
if (colorType === 'stroke') {
$inputCheckFilter.prop('disabled', true);
$inputCheckFilter.prop('checked', false);
} else {
$inputCheckTransparent.prop('disabled', false);
$inputCheckFilter.prop('disabled', false);
}
});
function onChangeShapeFill(event) {
var colorType = $selectColorType.val();
var isTransparent = $inputCheckTransparent.prop('checked');
var isFilter = $inputCheckFilter.prop('checked');
var shapeOption;
if (event.color) {
shapeOption = event.color;
} else if (isTransparent) {
shapeOption = 'transparent';
} else if (isFilter) {
shapeOption = {
type: 'filter',
filter: [{ pixelate: PIXELATE_FILTER_DEFAULT_VALUE }],
};
}
if (colorType === 'stroke') {
window['imageEditor'+editorNumber].changeShape(activeObjectId, {
stroke: shapeOption,
});
} else if (colorType === 'fill') {
window['imageEditor'+editorNumber].changeShape(activeObjectId, {
fill: shapeOption,
});
}
window['imageEditor'+editorNumber].setDrawingShape(shapeType, shapeOptions);
}
$inputStrokeWidthRange.on('change', function () {
var strokeWidth = Number($(this).val());
window['imageEditor'+editorNumber].changeShape(activeObjectId, {
strokeWidth: strokeWidth,
});
window['imageEditor'+editorNumber].setDrawingShape(shapeType, shapeOptions);
});
// control text mode
$btnText.on('click', function () {
//showSubMenu('text');
activateTextMode();
});
$inputFontSizeRange.on('change', function () {
window['imageEditor'+editorNumber].changeTextStyle(activeObjectId, {
fontSize: parseInt(this.value, 10),
});[]
});
$inputFontSizeList.on('change', function () {
window['imageEditor'+editorNumber].changeTextStyle(activeObjectId, {
fontSize: parseInt(this.value, 10),
});[]
});
//폰트 스타일 변경
$btnTextStyle.on('click', function (e) {
// eslint-disable-line
var styleType = $(this).attr('data-style-type');
var styleObj;
e.stopPropagation();
switch (styleType) {
case 'b':
styleObj = { fontWeight: 'bold' };
break;
case 'i':
styleObj = { fontStyle: 'italic' };
break;
case 'u':
styleObj = { underline: true };
break;
case 'l':
styleObj = { textAlign: 'left' };
break;
case 'c':
styleObj = { textAlign: 'center' };
break;
case 'r':
styleObj = { textAlign: 'right' };
break;
default:
styleObj = {};
}
if($(this).hasClass('active')){
$(this).removeClass('active');
}else{
$(this).addClass('active');
}
window['imageEditor'+editorNumber].changeTextStyle(activeObjectId, styleObj);
});
//폰트 변경
$btnTextFamily.on('change', function (e) {
// eslint-disable-line
var styleType = $(".btn-text-family option:selected").val();
var styleObj;
e.stopPropagation();
switch (styleType) {
case 'notoSans':
styleObj = { fontFamily: 'Noto Sans' };
break;
case 'tmonMonsori':
styleObj = { fontFamily: 'TmonMonsori' };
break;
case 'cafe24Dangdanghae':
styleObj = { fontFamily: 'Cafe24Dangdanghae' };
break;
case 'cafe24Ohsquare':
styleObj = { fontFamily: 'Cafe24Ohsquare' };
break;
case 'cafe24Simplehae':
styleObj = { fontFamily: 'Cafe24Simplehae' };
break;
case 'nanumSquareEB':
styleObj = { fontFamily: 'NanumSquareEB' };
break;
case 'nanumBarunGothicR':
styleObj = { fontFamily: 'NanumBarunGothicR' };
break;
case 'nanumBarunGothicB':
styleObj = { fontFamily: 'NanumBarunGothicB' };
break;
case 'nanumBarunGothicL':
styleObj = { fontFamily: 'NanumBarunGothicL' };
break;
default:
styleObj = {};
}
window['imageEditor'+editorNumber].changeTextStyle(activeObjectId, styleObj);
});
textColorpicker.on('selectColor', function (event) {
window['imageEditor'+editorNumber].changeTextStyle(activeObjectId, {
fill: event.color,
});
});
// control icon
$btnAddIcon.on('click', function () {
showSubMenu('icon');
activateIconMode();
});
function onClickIconSubMenu(event) {
var element = event.target || event.srcElement;
var iconType = $(element).attr('data-icon-type');
window['imageEditor'+editorNumber].once('mousedown', function (e, originPointer) {
window['imageEditor'+editorNumber]
.addIcon(iconType, {
left: originPointer.x,
top: originPointer.y,
})
.then(function (objectProps) {
// console.log(objectProps);
});
});
}
$btnRegisterIcon.on('click', function () {
$iconSubMenu
.find('.menu-item')
.eq(3)
.after('<li id="customArrow" class="menu-item icon-text" data-icon-type="customArrow">↑</li>');
window['imageEditor'+editorNumber].registerIcons({
customArrow: 'M 60 0 L 120 60 H 90 L 75 45 V 180 H 45 V 45 L 30 60 H 0 Z',
});
$btnRegisterIcon.off('click');
$iconSubMenu.on('click', '#customArrow', onClickIconSubMenu);
});
$iconSubMenu.on('click', '.icon-text', onClickIconSubMenu);
// control mask filter
$btnMaskFilter.on('click', function () {
window['imageEditor'+editorNumber].stopDrawingMode();
$displayingSubMenu.hide();
$displayingSubMenu = $filterSubMenu.show();
});
$btnImageFilter.on('click', function () {
var filters = {
grayscale: $inputCheckGrayscale,
invert: $inputCheckInvert,
sepia: $inputCheckSepia,
sepia2: $inputCheckSepia2,
blur: $inputCheckBlur,
shapren: $inputCheckSharpen,
emboss: $inputCheckEmboss,
removeWhite: $inputCheckRemoveWhite,
brightness: $inputCheckBrightness,
noise: $inputCheckNoise,
pixelate: $inputCheckPixelate,
tint: $inputCheckTint,
multiply: $inputCheckMultiply,
blend: $inputCheckBlend,
colorFilter: $inputCheckColorFilter,
};
tui.util.forEach(filters, function ($value, key) {
$value.prop('checked', window['imageEditor'+editorNumber].hasFilter(key));
});
$displayingSubMenu.hide();
$displayingSubMenu = $imageFilterSubMenu.show();
});
$btnLoadMaskImage.on('change', function () {
var file;
var imgUrl;
if (!supportingFileAPI) {
alert('This browser does not support file-api');
}
file = event.target.files[0];
if (file) {
imgUrl = URL.createObjectURL(file);
window['imageEditor'+editorNumber].loadImageFromURL(window['imageEditor'+editorNumber].toDataURL(), 'FilterImage').then(function () {
window['imageEditor'+editorNumber].addImageObject(imgUrl).then(function (objectProps) {
URL.revokeObjectURL(file);
console.log(objectProps);
});
});
}
});
$btnApplyMask.on('click', function () {
window['imageEditor'+editorNumber]
.applyFilter('mask', {
maskObjId: activeObjectId,
})
.then(function (result) {
console.log(result);
});
});
$inputCheckGrayscale.on('click', function () {
applyOrRemoveFilter($inputCheckGrayscale.val(), 'Grayscale', null);
if($inputCheckGrayscale.val() == "1") {
$inputCheckGrayscale.val("0");
} else {
$inputCheckGrayscale.val("1");
}
});
$inputCheckInvert.on('click', function () {
applyOrRemoveFilter($inputCheckInvert.val(), 'Invert', null);
if($inputCheckInvert.val() == "1") {
$inputCheckInvert.val("0");
} else {
$inputCheckInvert.val("1");
}
});
$inputCheckSepia.on('change', function () {
applyOrRemoveFilter(this.checked, 'Sepia', null);
});
$inputCheckSepia2.on('change', function () {
applyOrRemoveFilter(this.checked, 'vintage', null);
});
$inputCheckBlur.on('change', function () {
applyOrRemoveFilter(this.checked, 'Blur', { blur: 0.1 });
});
$inputCheckSharpen.on('change', function () {
applyOrRemoveFilter(this.checked, 'Sharpen', null);
});
$inputCheckEmboss.on('change', function () {
applyOrRemoveFilter(this.checked, 'Emboss', null);
});
$inputCheckRemoveWhite.on('change', function () {
applyOrRemoveFilter(this.checked, 'removeColor', {
color: '#FFFFFF',
useAlpha: false,
distance: parseInt($inputRangeRemoveWhiteDistance.val(), 10) / 255,
});
});
$inputRangeRemoveWhiteDistance.on('change', function () {
applyOrRemoveFilter($inputCheckRemoveWhite.is(':checked'), 'removeColor', {
distance: parseInt(this.value, 10) / 255,
});
});
$('[id^="input-check-brightness"]').on('click', function () {
var $inputRangeBrightnessValue = $("#input-range-brightness-value"+editorNumber);
var parseIntBrightnessValue = parseInt($inputRangeBrightnessValue.val());
var id = $(this).attr("id");
if(id == "input-check-brightness-dark") {
parseIntBrightnessValue = parseIntBrightnessValue - 15;
} else {
parseIntBrightnessValue = parseIntBrightnessValue + 15;
}
$inputRangeBrightnessValue.val(parseIntBrightnessValue);
applyOrRemoveFilter(true, 'brightness', {
brightness: parseIntBrightnessValue / 255,
});
});
$inputRangeBrightnessValue.on('change', function () {
applyOrRemoveFilter($inputCheckBrightness.is(':checked'), 'brightness', {
brightness: parseInt(this.value, 10) / 255,
});
});
$inputCheckNoise.on('change', function () {
applyOrRemoveFilter(this.checked, 'noise', {
noise: parseInt($inputRangeNoiseValue.val(), 10),
});
});
$inputRangeNoiseValue.on('change', function () {
applyOrRemoveFilter($inputCheckNoise.is(':checked'), 'noise', {
noise: parseInt(this.value, 10),
});
});
$inputCheckPixelate.on('change', function () {
applyOrRemoveFilter(this.checked, 'pixelate', {
blocksize: parseInt($inputRangePixelateValue.val(), 10),
});
});
$inputRangePixelateValue.on('change', function () {
applyOrRemoveFilter($inputCheckPixelate.is(':checked'), 'pixelate', {
blocksize: parseInt(this.value, 10),
});
});
$inputCheckTint.on('change', function () {
applyOrRemoveFilter(this.checked, 'blendColor', {
mode: 'tint',
color: tintColorpicker.getColor(),
alpha: parseFloat($inputRangeTintOpacityValue.val()),
});
});
$inputRangeTintOpacityValue.on('change', function () {
applyOrRemoveFilter($inputCheckTint.is(':checked'), 'blendColor', {
alpha: parseFloat($inputRangeTintOpacityValue.val()),
});
});
$inputCheckMultiply.on('change', function () {
applyOrRemoveFilter(this.checked, 'blendColor', {
color: multiplyColorpicker.getColor(),
});
});
$inputCheckBlend.on('change', function () {
applyOrRemoveFilter(this.checked, 'blendColor', {
mode: $selectBlendType.val(),
color: blendColorpicker.getColor(),
});
});
$selectBlendType.on('change', function () {
applyOrRemoveFilter($inputCheckBlend.is(':checked'), 'blendColor', {
mode: this.value,
});
});
$inputCheckColorFilter.on('change', function () {
applyOrRemoveFilter(this.checked, 'removeColor', {
color: '#FFFFFF',
distance: $inputRangeColorFilterValue.val() / 255,
});
});
$inputRangeColorFilterValue.on('change', function () {
applyOrRemoveFilter($inputCheckColorFilter.is(':checked'), 'removeColor', {
distance: this.value / 255,
});
});
// IE9 Unselectable
$('.menu').on('selectstart', function () {
return false;
});
var resizeImage = function (settings) {
var file = settings.file;
var maxSize = settings.maxSize;
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var resize = function () {
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
//return dataURItoBlob(dataUrl);
$("#imageSize"+editorNumber).text("이미지 사이즈: " + width + "x" + height);
return dataUrl;
};
return new Promise(function (ok, no) {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = function (readerEvent) {
image.onload = function () { return ok(resize()); };
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
});
};
//이미지를 캔버스에 그리기
function loadImageToCanvas(file, maxSize, eNumber) {
if (!eNumber) {
eNumber = editorNumber;
}
resizeImage({file:file, maxSize:maxSize}).then(function(dataUrl) {
setTimeout(function() {
window['imageEditor'+eNumber].loadImageFromURL(dataUrl, file.name).then(function (result) {
tabActive();
console.log(result);
window['imageEditor'+eNumber].clearUndoStack();
});
onImage(eNumber);
reloadPreview(dataUrl, eNumber);
}, 100);
});
}
//캔버스에 작업하던 이미지를 미리보기에 적용하기
function reloadPreview(dataUrl, eNumber, selectId) {
if (!eNumber) {
eNumber = editorNumber;
}
$(".preview"+eNumber).children("img").show();
if(selectId != "") {
$(".preview"+eNumber).children("img").addClass(selectId);
}
$(".preview"+eNumber).children("img").attr("src", dataUrl);
$(".preview"+eNumber).children("img").css({
"width" : "100%",
"height" : "150px"
});
$(".preview"+eNumber).children(".img_add").hide();
}
//이미지 삭제하기
function deleteImage(num) {
editorNumber = num;
$(".preview"+editorNumber).children("img").attr("src", "");
$(".preview"+editorNumber).children("img").hide();
offImage();
window['imageEditor'+editorNumber].loadImageFromURL('../../../../publish/images/popup/photo_editer_bg.jpg', 'SampleImage').then(function (sizeValue) {
console.log(sizeValue);
window['imageEditor'+editorNumber].clearUndoStack();
tabDisable();
});
$("#imageSize"+editorNumber).text("");
}
// 캔버스에 이미지가 있을 때 액션
function onImage(eNumber) {
if (!eNumber) {
eNumber = editorNumber;
}
$("#preview"+eNumber+" div").removeClass("no_img");
$(".preview"+eNumber).children(".img_add").hide();
$(".preview"+eNumber).children(".img_close").show();
$('#input-file'+eNumber).hide();
}
// 캔버스에 이미지가 없을 때 액션
function offImage(eNumber) {
if (!eNumber) {
eNumber = editorNumber;
}
$("#preview"+eNumber+" .preview"+eNumber).addClass("no_img");
$(".preview"+eNumber).children(".img_add").show();
$(".preview"+eNumber).children(".img_close").hide();
$('#input-file'+eNumber).show();
}
// 템플릿을 캔버스로
function selectTemplate(num,letterId) {
// 클릭 시 조회수 증가 로직
var url = "/web/mjon/msgdata/updateSmsTemplateCntAjax.do";
$.ajax({
type: "POST",
url: url,
data: {'letterId':letterId},
dataType:'json',
async: false,
cache: false,
success: function (returnData, status) {
console.log("status : ", status);
},
error: function (e) {console.log("ERROR : ", e); }
});
// 클릭 시 조회수 증가 로직 끝
var canvas = $("#tui-image-editor" + editorNumber + " > div > .lower-canvas");
var selectId = $("#img"+num).attr("class");
if(canvas.get(0).getContext){
var draw = canvas.get(0).getContext("2d");
var img = new Image();
var src = $('#img'+num).attr("src");
img.src = src;
img.onload = function(){
canvas.get(0).width = img.width;
canvas.get(0).height = img.height;
$("#tui-image-editor" + editorNumber + " > .tui-image-editor-canvas-container").height(img.height);
$("#tui-image-editor" + editorNumber + " > .tui-image-editor-canvas-container").width(img.width);
$("#imageSize"+editorNumber).text("이미지 사이즈: " + img.width + "x" + img.height);
window['imageEditor'+editorNumber].loadImageFromURL(img.src, 'Template');
onImage();
reloadPreview(img.src, editorNumber, selectId);
}
}
tabActive();
}
// 스티커 / 포토편집 탭 비활성화 해제
function tabActive() {
$(".tabType3").children("li.tab").removeClass("disable");
$(".tabType3").children("li.tab:nth-child(3)").find("a").attr("onclick","TabType3(this,'3')");
$(".tabType3").children("li.tab:nth-child(4)").find("a").attr("onclick","TabType3(this,'4')");
}
//스티커 / 포토편집 탭 비활성화
function tabDisable() {
$(".tabType3").children("li.tab:nth-child(3)").addClass("disable");
$(".tabType3").children("li.tab:nth-child(4)").addClass("disable");
$(".tabType3").children("li.tab:nth-child(3)").find("a").removeAttr("onclick");
$(".tabType3").children("li.tab:nth-child(4)").find("a").removeAttr("onclick");
//현재탭을 "추천템플릿"탭으로 변경
var $tab = $(".tabType3").children("li.tab:nth-child(2)");
$tab.addClass("active");
$tab.find("a").attr("title","선택됨");
$tab.siblings("li.tab").removeClass("active");
$tab.siblings("li.tab").find("a").removeAttr("title");
var $tabCn = $("#tab3_2");
$tabCn.fadeIn(0);
$tabCn.addClass("current");
$(".header_cont").not($tabCn).removeClass("current");
$(".header_cont").not($tabCn).fadeOut(0);
currTabId = "2";
}
// text size 칸 비우기
function deleteValue() {
$("#input-font-size-range").val("");
}
// 파일 리스트 번호
var fileIndex = 0;
// 등록할 전체 파일 사이즈
var totalFileSize = 0;
// 파일 리스트
var fileList = new Array();
// 파일 사이즈 리스트
var fileSizeList = new Array();
// 등록 가능한 파일 사이즈 MB
var uploadSize = 10;
// 등록 가능한 총 파일 사이즈 MB
var maxUploadSize = 30;
$(function (){
// 파일 드롭 다운
fileDropDown();
});
// 파일 드롭 다운
function fileDropDown(){
var dropZone = $(".preview");
//Drag기능
dropZone.on('dragenter',function(e){
e.stopPropagation();
e.preventDefault();
// 드롭다운 영역 css
$(this).css('background-color','#E3F2FC');
});
dropZone.on('dragleave',function(e){
e.stopPropagation();
e.preventDefault();
// 드롭다운 영역 css
$(this).css('background-color','');
});
dropZone.on('dragover',function(e){
e.stopPropagation();
e.preventDefault();
// 드롭다운 영역 css
$(this).css('background-color','#E3F2FC');
});
dropZone.on('drop',function(e){
e.preventDefault();
// 드롭다운 영역 css
dropZone.css('background-color','');
var dropId = $(this).attr("id");
editorNumber = dropId.charAt(dropId.length -1);
var files = e.originalEvent.dataTransfer.files;
if(files != null){
if(files.length < 1){
alert("폴더 업로드 불가");
return;
}
selectFile(files)
}else{
alert("ERROR");
}
});
}
// 파일 선택시
function selectFile(files){
// 다중파일 등록
if(files != null){
var emptyCanvasLength = $(".no_img").length;
var j = 1;
if(emptyCanvasLength == 0) {
alert("빈 캔버스가 없습니다.")
return;
}
if(emptyCanvasLength < files.length) {
alert("최대 "+ emptyCanvasLength + "개의 이미지를 업로드 해주세요.")
return;
}
for(let i = 0; i < files.length; ++i){
// 파일 이름
var fileName = files[i].name;
var fileNameArr = fileName.split("\.");
// 확장자
var ext = fileNameArr[fileNameArr.length - 1];
// 파일 사이즈(단위 :MB)
var fileSize = files[i].size / 1024 / 1024;
if(fileSize > uploadSize){
// 파일 사이즈 체크
alert("용량 초과\n업로드 가능 용량 : " + uploadSize + " MB");
break;
}else{
// 전체 파일 사이즈
totalFileSize += fileSize;
// 파일 배열에 넣기
fileList[fileIndex] = files[i];
// 파일 사이즈 배열에 넣기
fileSizeList[fileIndex] = fileSize;
//캔버스에 이미지 올리기
if (!supportingFileAPI) {
alert('This browser does not support file-api');
}
if(files.length != 1) {
for(j; j<=3; j++) {
var canvasEmptyCheck = $("#preview"+j+" .no_img").length;
if(canvasEmptyCheck == 1) { // 캔버스가 비어있으면
editorNumber = j;
loadImageToCanvas(files[i], 960, editorNumber);
j = j+1;
break;
}
}
} else {
loadImageToCanvas(files[i], 960);
}
//썸네일 영역에 캔버스 이미지 url로 이미지 쓰기
canvasTab(editorNumber);
// 파일 번호 증가
fileIndex++;
}
}
}else{
alert("ERROR");
}
}
//Etc..
//Load sample image
imageEditor1.loadImageFromURL('../../../../publish/images/popup/photo_editer_bg.jpg', 'SampleImage').then(function (sizeValue) {
console.log(sizeValue);
imageEditor1.clearUndoStack();
});
//Load sample image
imageEditor2.loadImageFromURL('../../../../publish/images/popup/photo_editer_bg.jpg', 'SampleImage').then(function (sizeValue) {
console.log(sizeValue);
imageEditor2.clearUndoStack();
});
//Load sample image
imageEditor3.loadImageFromURL('../../../../publish/images/popup/photo_editer_bg.jpg', 'SampleImage').then(function (sizeValue) {
console.log(sizeValue);
imageEditor3.clearUndoStack();
});