// GLOBALS
var LOG = false; //false; // ENABLE LOGGING
var PRLOG = false; //false; /** PRICE LOG - REMOVE COMMENTS **/
var INPUTDELAY = 650; // Milliseconds
var FLOATDELAY = 1300 // Milliseconds for Float Inputs
var SCONFIG = '';
var PHPCALC = false; /** ENABLES PHP + JS CALC COMPARE MODE - HAS TO BE FALSE IN LIVE MODE **/
var xhr = '';
var canvas = new Object();
var bgLayer = new Object();
var miniView = new Object();
var SIGN = { width: 550, maxWidth: 728,
height: 300, maxHeight: 470,
color:'#000000',
bgcolor:'#ffffff',
border: 0,
borderDistance: 10,
fonts: {},
fontVectorizeOpacity: 0, //0.1 for test
selectorPadding: 0,
selectorCornerSize: 10,
selectorBorderColor: '#3260AB', //'#0093db',
selectorCornerColor: '#3260AB',
selectorCornerStyle: 'circle',
selectorCornerTransparent: false,
selectorSerienText : '#673086',
scale:'1:1',
scaleFac:1,
dimMax:600,
dimMin:300,
cutFormColor: 'rgba(220,220,220,1)', //'rgba(241,241,241,1)'
cornerRadius: 3, // in mm
calculateOnUnload: 0,
cutFormStrokeWidth: 1.5,
cutFormStrokeColor:'rgba(200,0,0,1)',
cutFormStrokeDashWidth: 5,
fixationDefaultID: 0,
fixationDefaultDistance: 6.25,
fixationDefaultDiameter: 4.5,
fixationDefaultRadius: 2.25,
fixationDefaultDistanceEdge: 4,
lockRotate: 1,
clipping: 0,
miniViewWidth: 200,
miniViewHeight: 110,
miniViewRefreshDelay: 125, // ms
fillColors: {'rgba(255,0,0,0.95)':'Rot','rgba(0,0,255,0.95)':'Blau','rgba(0,0,0,0.95)':'Schwarz',
'rgba(0,255,0,0.95)':'Grün','rgba(255,255,255,0.95)':'Weiss','rgba(255,255,0,0.95)':'Gelb'
},
oldTemplate: false,
errorDelay: 5000, //ms
error: {},
warn : {},
closeMenuAfterAdd: false,
blockClickEvents: false,
vectorizableFonts: { 'Black Ops One' : {'cssName': 'SST_BlackOpsOne','regular': 1, 'italic': 0, 'bold': 0, 'bolditalic': 0, 'cutform' : 1 },'Bungee' : {'cssName': 'SST_Bungee','regular': 1, 'italic': 0, 'bold': 0, 'bolditalic': 0, 'cutform' : 0 },'Cinzel Decorative' : {'cssName': 'SST_CinzelDecorative','regular': 1, 'italic': 0, 'bold': 1, 'bolditalic': 0, 'cutform' : 0 },'Courier Prime' : {'cssName': 'SST_CourierPrime','regular': 1, 'italic': 1, 'bold': 1, 'bolditalic': 1, 'cutform' : 0 },'Dancing Script' : {'cssName': 'SST_DancingScript','regular': 1, 'italic': 0, 'bold': 1, 'bolditalic': 0, 'cutform' : 0 },'Elemental End' : {'cssName': 'SST_ElementalEnd','regular': 1, 'italic': 1, 'bold': 0, 'bolditalic': 0, 'cutform' : 0 },'Linden Hill' : {'cssName': 'SST_LindenHill','regular': 1, 'italic': 1, 'bold': 0, 'bolditalic': 0, 'cutform' : 0 },'Montserrat' : {'cssName': 'SST_Montserrat','regular': 1, 'italic': 1, 'bold': 1, 'bolditalic': 1, 'cutform' : 0 },'Protest Guerrilla' : {'cssName': 'SST_ProtestGuerrilla','regular': 1, 'italic': 0, 'bold': 0, 'bolditalic': 0, 'cutform' : 1 },'Saira Stencil One' : {'cssName': 'SST_SairaStencilOne','regular': 1, 'italic': 0, 'bold': 0, 'bolditalic': 0, 'cutform' : 1 },'Sansita' : {'cssName': 'SST_Sansita','regular': 1, 'italic': 1, 'bold': 1, 'bolditalic': 1, 'cutform' : 0 },'Satisfy' : {'cssName': 'SST_Satisfy','regular': 1, 'italic': 0, 'bold': 0, 'bolditalic': 0, 'cutform' : 0 },'Space Mono' : {'cssName': 'SST_SpaceMono','regular': 1, 'italic': 1, 'bold': 1, 'bolditalic': 1, 'cutform' : 0 },'Stick' : {'cssName': 'SST_Stick','regular': 1, 'italic': 0, 'bold': 0, 'bolditalic': 0, 'cutform' : 1 },'Tillana' : {'cssName': 'SST_Tillana','regular': 1, 'italic': 0, 'bold': 1, 'bolditalic': 0, 'cutform' : 0 },'Ubuntu' : {'cssName': 'SST_Ubuntu','regular': 1, 'italic': 1, 'bold': 1, 'bolditalic': 1, 'cutform' : 0 },'Vollkorn SC' : {'cssName': 'SST_VollkornSC','regular': 1, 'italic': 0, 'bold': 1, 'bolditalic': 0, 'cutform' : 0 } },
nonVectorizableFonts: { },
defaultFont: 'SST_Ubuntu'
};
/* Click listener to slow down click events */
document.addEventListener("click", e => { if (SIGN.blockClickEvents) { e.stopPropagation(); e.preventDefault(); }}, true);
var FIXDATA= new Array();
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$.ajaxSetup({ cache: false });
/** ---------------------------------------------------------------------------*/
/** INIT EVENTS */
/** ---------------------------------------------------------------------------*/
$(document).ready(function()
{
SCONFIG = $('#JSCONFIG').val();
fabric.Object.NUM_FRACTION_DIGITS = 17;
fabric.textureSize = 4096;
if (fabric.isWebglSupported()) { fabric.textureSize = 65536; }
//fabric.filterBackend = fabric.initFilterBackend(); //this will init WebGL
//fabric.textureSize = fabric.maxTextureSize; //allows larger images
fabric.initFilterBackend = function() {
if (fabric.enableGLFiltering && fabric.isWebglSupported && fabric.isWebglSupported(fabric.textureSize)) {
console.log('max texture size: ' + fabric.maxTextureSize);
return (new fabric.WebglFilterBackend({ tileSize: fabric.textureSize }));
}
else if (fabric.Canvas2dFilterBackend) {
return (new fabric.Canvas2dFilterBackend());
}
};
/** MINI VIEW **/
miniView = this.__canvas = new fabric.StaticCanvas('miniView');
//miniView = this.__canvas = new fabric.Canvas('miniView');
miniView.stateful = false; // Increases speed (if undone function not needed)
miniView.selection = false;
miniView.preserveObjectStacking = true;
miniView.setWidth(SIGN.miniViewWidth);
miniView.setHeight(SIGN.miniViewHeight);
if(document.getElementById('schild')===null)
{
return;
}
else
{ canvas = this.__canvas = new fabric.Canvas('schild');
//canvas = this.__canvas = new fabric.Canvas('schild', { imageSmoothingEnabled: false, enableRetinaScaling: false,});
// CANVAS EVENTS
canvas.on({'object:moving': function () { updateObjControls('obj_moving')},
'object:scaling': function () { updateObjControls('obj_scaling')},
'object:resizing': function () { updateObjControls('obj_resizing')},
'object:rotating': function () { updateObjControls('obj_rotating')},
'object:selected': function () { updateObjControls('obj_selected')},
'object:modified': function () { updateObjControls('obj_modified')},
'selection:created': function () { updateObjControls('selection:created')},
'selection:updated': function () { updateObjControls('selection:updated')},
'selection:cleared': function () { $('#objectEdit').hide(); hideBlackWhiteControl(); updateObjControls('selection:cleared')},
'before:selection:cleared': hideObjControls,
'text:editing:entered': function () { LOG && console.log('Event: text_editing_entered'); },
'text:editing:exited': function () { var obj = canvas.getActiveObject();
if(obj) { if(obj.mmkLayerType=='layerVectorEditor')
{ canvas.fire('object:modified'); canvas.discardActiveObject(); }}
LOG && console.log('Event: text:editing:exited'); },
'text:selection:changed': function () { LOG && console.log('Event: text_editing_changed'); },
'text:changed': function ()
{
var obj = canvas.getActiveObject();
if(obj)
{
var parsedText = filterUCChars(obj.get('text'),$('#textBox').val());
obj.set({'text': parsedText}); //$(this).val()
$('#textBox').val(parsedText);
canvas.renderAll();
}
LOG && console.log('Event: text_changed');
},
//'mouse:down': function() { LOG && console.log('Event: mouse:down'); },
'mouse:dblclick': async function()
{
var obj = canvas.getActiveObject();
if(obj && obj.mmkLayerType=='layerVectorResult')
{
if(obj.mmkSerienText)
{
serienDruckWin.open();
}
else
{ await editVectorizedFont(obj); }
}
if(obj && obj.mmkLayerType=='layerBarcode')
{ restoreBarcode(); }
},
'mouse:up': function()
{
var obj = canvas.getActiveObject();
if(obj) { calculateSign('Event: mouse up',0);
checkObjectMinimumHeight(obj);
checkQRCodeHeight(obj);
}
//refreshMiniView();
},
'after:render': function() { this.calcOffset(); }
});
}
canvas.stateful = false; // Increases speed (if undone function not needed)
canvas.selection = false;
canvas.controlsAboveOverlay = true;
//canvas.renderOnAddRemove = false; // better?
canvas.preserveObjectStacking = true; // ensure objects are not at front on selection
canvas.setWidth($('#canvasBox').width());
canvas.setHeight($('#canvasBox').height());
initCenteringGuidelines(canvas);
initAligningGuidelines(canvas);
showZoomDim('canvasInitialize');
/** SPECIAL ICON DELETE */
var deleteIcon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2ZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3M0E3NEZDNDQ2NTBFQzExQUJFQkJBRjBGNjU0RkE4MiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpDNzI5NUU3OTU0RDExMUVGOEM2QkY3NDY2ODA2NDRGMyIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpDNzI5NUU3ODU0RDExMUVGOEM2QkY3NDY2ODA2NDRGMyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M2IChXaW5kb3dzKSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjczQTc0RkM0NDY1MEVDMTFBQkVCQkFGMEY2NTRGQTgyIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjczQTc0RkM0NDY1MEVDMTFBQkVCQkFGMEY2NTRGQTgyIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+FlWenQAAAUBJREFUeNpi/P//P8NAAhZkjnHiGl8gVQjEpkDMQ2W7vgDxaSDuOzs/ZAtMkBEWAkDLW4BUNZ083gp0RA3cAUDLfYDszXQOfT+gIzYzQTlFAxD9oKhmgDnAZAAcYILsAN4BcAAvsgMGRzYkFjgaSzNUxRkxCPGxg/nvP/9kaJl/luHA+Wckm0VWCCBbDgKCvOwM1QnGtAsBdB9jAyA5YLYiOUSYyPExIUBKiBAVAq75tCujBjwXkOQAUByDMDMTI5h/em4wXv7wC4FRB4w6YNBURjrKQgx//vxjYIJmN3Q+zR0wr8oRL59mUfAL6Eti1JDS0icpBCxT1w3fXPB5AOz+guyAMwPggNPIDugfAAf0wx0A6qGAukt0tLwVaieibwjtH/oDqXwgNgNibipb+hWITwHxBKDlmzA6pwMFAAIMAKGBamYIUSIHAAAAAElFTkSuQmCC";
var deleteImg = document.createElement('img');
deleteImg.src = deleteIcon;
function renderIcon(icon) {
return function renderIcon(ctx, left, top, styleOverride, fabricObject) {
var size = this.cornerSize;
ctx.save();
ctx.translate(left, top);
ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
ctx.drawImage(icon, -size/2, -size/2, size, size);
ctx.restore();
}
}
fabric.Object.prototype.controls.deleteControl = new fabric.Control({
x: 0.5,
y: -0.5,
offsetY: -20,
offsetX: 20,
sizeX: 32,
sizeY: 32,
cursorStyle: 'pointer',
mouseUpHandler: deleteObject,
//mouseUpHandler: removeObj(),
render: renderIcon(deleteImg),
cornerSize: 32
});
function deleteObject(eventData, transform)
{
var target = transform.target;
var canvas = target.canvas;
/** canvas.remove(target); **/
removeObj();
canvas.requestRenderAll();
}
// TO 1.2 on init ( 1/3 )
// canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), 1.2);
// console.log('CANVAS SIZE ON INIT:' + $('#canvasBox').width() + ', ' + $('#canvasBox').height());
// DIM
//$('#DIMMODE0').on('click', function() { var dim = $('#DIMSTD').val().split('x'); resizeBack(dim[0],dim[1]); $('#WIDTH').val(dim[0]); $('#HEIGHT').val(dim[1]); });
$('#DIMMODE0').on('click', function() { var dim = $('#DIMSTD').val().split('x'); $('#WIDTH').val(dim[0]); $('#HEIGHT').val(dim[1]); resizeBack(dim[0],dim[1]); });
$('#DIMMODE1').on('click', function() { resizeBack($('#WIDTH').val(),$('#HEIGHT').val())});
$('#DIMSTD').change(function()
{
$("#DIMMODE0").prop("checked", true);
var dim = $(this).val().split('x');
$('#WIDTH').val(dim[0]);
$('#HEIGHT').val(dim[1]);
resizeBack(dim[0],dim[1]);
});
$('#WIDTH, #HEIGHT').bind({
blur: function(ev)
{
if(checkSignWidthHeight($('#WIDTH').val(),$('#HEIGHT').val())==true)
{ $("#DIMMODE1").prop("checked", true); resizeBack($('#WIDTH').val(),$('#HEIGHT').val()); }
else
{ var dim = $('#DIMSTD').val().split('x'); $('#WIDTH').val(dim[0]); $('#HEIGHT').val(dim[1]); resizeBack(dim[0],dim[1]); }
},
keydown: function(ev)
{
if(isNaN(ev.key) && ev.key !== 'Backspace') {
ev.preventDefault();
}
if(ev.which==13 || ev.which==9)
{
if(ev.which==13) { ev.preventDefault(); }
if(checkSignWidthHeight($('#WIDTH').val(),$('#HEIGHT').val())==true)
{ $("#DIMMODE1").prop("checked", true); resizeBack($('#WIDTH').val(),$('#HEIGHT').val()); }
else { var dim = $('#DIMSTD').val().split('x'); $('#WIDTH').val(dim[0]); $('#HEIGHT').val(dim[1]); resizeBack(dim[0],dim[1]); }
}
else
{
delay(function()
{
if(checkSignWidthHeight($('#WIDTH').val(),$('#HEIGHT').val())==true)
{ $("#DIMMODE1").prop("checked", true); resizeBack($('#WIDTH').val(),$('#HEIGHT').val()); }
else { var dim = $('#DIMSTD').val().split('x'); $('#WIDTH').val(dim[0]); $('#HEIGHT').val(dim[1]); resizeBack(dim[0],dim[1]); }
}, FLOATDELAY );
}
}
});
// COLORS
$('#SLIDERCOLORS').on('click','.matColor', function()
{
$('#ENGRAVEMETHOD').val($(this).data('emid'));
changeBackColor('schild',$(this).data('color'),$(this).data('colorbg'),$(this).data('colorname'),$(this).data('colorid'),$(this).data('colorbgimage'),$(this).data('colorgroupid'),1);
});
// TEXT
$('#textFontSelector').on('mousedown', function (e)
{
e.preventDefault(); this.blur(); window.focus();
$('#textFontList').is(':hidden') ? $('#textFontList').show() : $('#textFontList').hide();
});
$('.textFontSelector').on('mousedown', function (e)
{
e.preventDefault(); this.blur(); window.focus();
$('.textFontList').is(':hidden') ? $('.textFontList').show() : $('.textFontList').hide();
});
$('#textCutFontSelector').on('mousedown', function (e)
{
e.preventDefault(); this.blur(); window.focus();
$('#textCutFontList').is(':hidden') ? $('#textCutFontList').show() : $('#textCutFontList').hide();
});
$('.textCutFontSelector').on('mousedown', function (e)
{
e.preventDefault(); this.blur(); window.focus();
$('.textCutFontList').is(':hidden') ? $('.textCutFontList').show() : $('.textCutFontList').hide();
});
$('#textSize, #textCutSize').keyup(function(e)
{
delay(function() {
var obj = canvas.getActiveObject();
var target = e.delegateTarget;
//if(checkTextHeight($('#textSize').val())==true)
if(checkTextHeight($(target).val())==true)
{
updateObjFromControls('scaleText');
}
else
{
//$('#textSize').val($('#objHeight').val());
$(target).val($('#objHeight').val());
}
}, FLOATDELAY );
});
$('#textBox, #textCutBox').on('input', function(e) {
var obj = canvas.getActiveObject();
var target = e.delegateTarget;
///var selStart = $('#textBox').prop('selectionStart');
var selStart = $(target).prop('selectionStart');
//console.log(selStart);
if(obj.type=='group' && obj.mmkLayerType=='layerVectorResult')
{
editVectorizedFont(obj);
//$('#textBox').prop('selectionEnd', selStart);
//$('#textBox').focus();
$(target).prop('selectionEnd', selStart);
$(target).focus();
}
var parsedText = filterUCChars($(this).val(),obj.get('text'));
obj.set({'text': parsedText}); //$(this).val()
$(this).val(parsedText);
canvas.renderAll();
updateObjControls('input_textBox');
});
// FIRE MODIFIED FOR PRICE DISPLAY REFRESH (ON VECTOR FONTS)
$('#createTools').on('click','.menuCloseButton, .menuCloseOkButton, menuNextSubButton', function()
{
canvas.fire('object:modified');
});
// SERIENTEXT
$('#applySerienText').on('click', function()
{
$('#applySerienText').prop('disabled',true);
// SEARCH FOR ACTIVE SERIENTEXT OBJECT
var actObj= new Object;
var serienTextObject=0;
for(x=0; x < canvas.getObjects().length; x++)
{
obj=canvas.item(x);
//if(obj.mmkLayerType=='layerSerienText')
if(obj.mmkSerienText)
{
canvas.setActiveObject(obj);
serienTextObject=1;
actObj=obj;
break;
}
}
// AJAX UPDATE REQUEST
var zeilen = $('input[name="stFields[]"]').map(function(){ return this.value; }).get();
var zcheck = '';
for (var i=0; i < zeilen.length; i++)
{
zcheck = zcheck + zeilen[i].replace(',','');
}
if(zcheck.length==0) { alert('Bitte legen Sie mindestens 1 Entwurf an. Geben Sie dazu einen Text ein'); return false; }
$.when(calculateSign('#applySerienText event',1)).done(function(ev)
{
$.ajax({url: 'https://schilderstyle.de/konfigurator/scripts/mmk-io.php',
type: 'POST',
cache: true,
dataType: "text",
data: {'com': 'updateTxtMode', stFields: zeilen},
error: function(em)
{
$('#applySerienText').prop('disabled',false);
return true;
},
success: function(st)
{
if(st.length==0)
{
$('#serientext').hide();
$('#noSerienText').show();
$('#TXTMODE').val(0);
$('#TXTDATA').val('');
$('#TXTMODESIGNS').val(0);
}
else
{
$('#serientext').show();
$('#noSerienText').hide();
if(serienTextObject==0) // CREATE
{
rows = addSerienText(st);
$('#TXTMODE').val(1);
$('#TXTDATA').val(st);
$('#TXTMODESIGNS').val(rows);
}
else
{
rows = updateSerienText(st,actObj)
$('#TXTMODE').val(1);
$('#TXTDATA').val(st);
$('#TXTMODESIGNS').val(rows);
}
rows==1 ? $('#stSignDisplay').text(rows+ ' Entwurf') : $('#stSignDisplay').text(rows+ ' Entw\u00fcrfe');
$('#MENGE').val(rows);
$('#MENGE').prop('readonly', true);
calculateSign('Event: Click #applySerientext',0);
}
serienDruckWin.close();
$('#applySerienText').prop('disabled',false);
return true;
}
});
});
$('#applySerienText').prop('disabled',false);
return false;
});
// IMAGE CATEGORIES
//$('#IMGCATEGORIES').on('change', function() {
//var id = ;
//selectImageCat($('#IMGCATEGORIES option:selected').val())
//});
// BEFESTIGUNGEN
$('#SLIDERFIXATIONS').on('click', '.fixations', function(e)
{
//if(confirm('Wenn Sie die Befestigung ändern werden ggf. alle Ihre bisherigen Einstellungen verworfen.')==true)
//{
addFixation($(this).data('fxid'),$(this).data('dpimage'),$(this).data('fxname'),$(this).data('dc'));
showFixationDetails($(this));
//}
//else
//{
//e.stopPropagation();
//}
});
// BEFESTIGUNGEN / LOCHDURCHMESSER
$('#fixVertikal1').keyup(function() { delay(function() { checkFixationInput($('#fixVertikal1').val(),'#fixVertikal1',1); setFixation(1); }, FLOATDELAY ); });
$('#fixHorizontal2').keyup(function() { delay(function() { checkFixationInput($('#fixHorizontal2').val(),'#fixHorizontal2',2); setFixation(2); }, FLOATDELAY ); });
$('#fixHorizontal4').keyup(function() { delay(function() { checkFixationInput($('#fixHorizontal4').val(),'#fixHorizontal4',4); setFixation(4); }, FLOATDELAY ); });
$('#fixVertikal4').keyup(function() { delay(function() { checkFixationInput($('#fixVertikal4').val(),'#fixVertikal4',4); setFixation(4); }, FLOATDELAY ); });
$('#fixDiameter').keyup(function() { delay(function() { checkFixationInput($('#fixDiameter').val(),'#fixDiameter','diameter'); var mode = parseFloat($('#fixEditMode').val()); setFixation(mode); }, FLOATDELAY ); });
// KOMPONENTEN
$('#SLIDERCOMPONENTS').on('click','.components', function(e)
{
if($(e.target).attr('class')!='crtMenuSubLinkComponents')
{ addComponent($(this).data('cpid'),"","$(this).data('cpname')",1); }
});
// BIND KEY EVENTS
//$('html').bind('keypress', function(e)
//{
// if(e.keyCode == 39)
// {
// setTimeout(function() {
// e.target.value += String.fromCharCode(8217); //'’';
// }, 4);
// e.preventDefault(); //return '`'; // replace apostrophe with pseudp char to avoid json bugs;
// }
//});
$('html').keyup(function(e)
{
if(e.keyCode == 46)
{
var hasFocus=0;
$("input").each(function() { if($(this).is(':focus')) { hasFocus=1; }});
$("textarea").each(function() { if($(this).is(':focus')) { hasFocus=1; }});
if(hasFocus==0) { removeObj(); }
}
});
// PROBLEMS WITH MOBILE
//$('html').keydown(function(e)
//{
// switch(e.keyCode)
// {
// case 37: formBlurAll(); moveObj('left'); break;
// case 38: formBlurAll(); moveObj('up'); break;
// case 39: formBlurAll(); moveObj('right'); break;
// case 40: formBlurAll(); moveObj('down'); break;
// }
//});
// LOADER / SAVER
$('.loadSignRow').on('click',function()
{ $(this).find('input').prop('checked',true); });
$('#mmkback').on('click','.loadSignTemplate',function()
{ loadSign($(this).data('mode'),$(this).data('id'),$(this).data('url')); });
$('#mmkback').on('click','.loadSignTemplateKat',function()
{ loadTemplates($(this).data('id'),$(this).data('name')); });
// INFOBAR FUNC
$('#MENGE').keyup(function()
{
delay(function() {
if($('#MENGE').val() >= 1 && $('#MENGE').val() <=99999) {}
else { $('#MENGE').val(1); }
calculateSign('Event: Enter #Menge',0);
}, INPUTDELAY );
});
var oldStaerke, cEngrave;
$('#STAERKE').on('click', function() {
oldStaerke = $('#STAERKE option:selected').val();
});
$('#STAERKE').on('change', function()
{
changeStaerke($('#MATERIALID').val(),$('#STAERKE').val(), oldStaerke);
});
$('#ENGRAVEMETHOD').on('change', function()
{
changeMaterialJS($('#MATERIALID').val(),$('#PRODUCTID').val(),'');
});
$('#objXPos, #objYPos').bind({
blur: function(ev)
{
var dim = $(this).attr('id');
var obj = canvas.getActiveObject();
if(checkObjectXY($('#objXPos').val(),$('#objYPos').val())==true)
{ dim == 'objXPos' ? updateObjFromControls('posX'):updateObjFromControls('posY'); }
else { setCalculateObjXY(obj); }
},
keydown: function(ev)
{
var dim = $(this).attr('id');
if(ev.which==13 || ev.which==9)
{
if(ev.which==13) { ev.preventDefault(); }
var obj = canvas.getActiveObject();
if(checkObjectXY($('#objXPos').val(),$('#objYPos').val())==true)
{ dim == 'objXPos' ? updateObjFromControls('posX'):updateObjFromControls('posY'); }
else { setCalculateObjXY(obj); }
}
else
{
delay(function() {
var obj = canvas.getActiveObject();
if(checkObjectXY($('#objXPos').val(),$('#objYPos').val())==true)
{ dim == 'objXPos' ? updateObjFromControls('posX'): updateObjFromControls('posY'); }
else { setCalculateObjXY(obj);}
}, FLOATDELAY );
}
}
});
$('#objWidth, #objHeight').bind({
blur: function(ev)
{
var dim = $(this).attr('id');
if(checkObjectWidthHeight($('#objWidth').val(),$('#objHeight').val())==true)
{
dim == 'objWidth' ? updateObjFromControls('scaleX') : updateObjFromControls('scaleY');
}
else { restoreObjWidthHeight(obj); }
},
keydown: function(ev)
{
var dim = $(this).attr('id');
if(ev.which==13 || ev.which==9)
{
if(ev.which==13) { ev.preventDefault(); }
var obj = canvas.getActiveObject();
if(checkObjectWidthHeight($('#objWidth').val(),$('#objHeight').val())==true)
{
dim == 'objWidth' ? updateObjFromControls('scaleX') : updateObjFromControls('scaleY');
}
else { restoreObjWidthHeight(obj); }
}
else
{
delay(function() {
var obj = canvas.getActiveObject();
if(checkObjectWidthHeight($('#objWidth').val(),$('#objHeight').val())==true)
{
dim == 'objWidth' ? updateObjFromControls('scaleX') : updateObjFromControls('scaleY');
}
else
{ restoreObjWidthHeight(obj); }
}, FLOATDELAY );
}
}
});
$('#objAngle').bind({
blur: function(ev) { updateObjFromControls('angle'); },
keydown: function(ev)
{
if(isNaN(ev.key) && ev.key !== 'Backspace') {
ev.preventDefault();
}
if(ev.which==13 || ev.which==9)
{
if(ev.which==13) { ev.preventDefault(); }
updateObjFromControls('angle');
}
else
{
delay(function() {
updateObjFromControls('angle');
}, INPUTDELAY );
}
}
});
$('#objLockRotate').on('click', function()
{
SIGN.lockRotate = SIGN.lockRotate == 1 ? 0: 1;
var lockImg = SIGN.lockRotate == 1 ? '../../../konfigurator/icons/create_lock_rotate.svg' : '../../../konfigurator/icons/create_unlock_rotate.svg';
var lockRotateInput = SIGN.lockRotate == 1 ? true:false;
var lockTitle = SIGN.lockRotate == 1 ? 'Drehung entsperren':'Drehung sperren';
$('#objLockRotateImg').attr('src',lockImg)
$('#objLockRotateImg').attr('title',lockTitle)
$('#objLockRotateImg').attr('alt',lockTitle)
$('#objAngle').prop('disabled',lockRotateInput);
for(x=2; x < canvas.getObjects().length; x++)
{
formatObjControls(canvas.item(x),1);
}
canvas.renderAll();
});
$('.blackWhiteControl').on('change', function() { setBlackWhiteFilter(); })
$('.moveObjBack').on('click',function() { moveObj('moveObjBack'); });
$('.moveObjFront').on('click',function() { moveObj('moveObjFront'); });
$('.moveObjToFront').on('click',function() { moveObj('moveObjToFront'); });
// ZOOM + PREVIEW
$('.previewSign').on('click', function() { showSignPreview(); });
$('.zoomin').on('click', function() { setCanvasZoom('inc'); });
$('.zoomout').on('click', function() { setCanvasZoom('dec'); });
// RESPONSIVE EDIT BUTTON
$('#respObjectEditButton').on('click',function()
{
$('#objectEdit').toggle(); // maybe nonsene, because there is similar event
closeMenues();
});
// ANFRAGE
$('#applyAnfrage').on('click', function() { createAnfrage(); });
// LAYER LIST
$(document).on('click', '.schildObjLayer', function() { selectObjListLayer($(this).data('layerid'),'click'); });
$(document).on('dblclick','.schildObjLayer', function() { selectObjListLayer($(this).data('layerid'),'dblclick'); });
// BEFOREUNLOAD
//console.log(window.location.href , 'https://schilderstyle.de/konfigurator/2/create/');
$(window).on('unload', function()
{
if(SIGN.calculateOnUnload==1)
{
if(window.location.href=='https://schilderstyle.de/konfigurator/2/create/')
{
calculateSign('fromUnloadEvent()',2);
}
}
});
// RESIZE LISTENER
$(window).resize(function()
{
//console.log('window resize from mmc');
//canvas.discardActiveObject();
setCanvasZoomInit('Resize Event');
setBlackWhiteControlPos();
});
// PARSER FOR OLD JSON PATH GROUP (NO LONGER NEEDED???)
fabric.PathGroup = { };
fabric.PathGroup.fromObject = function(object, callback) {
var originalPaths = object.paths;
delete object.paths;
if (typeof originalPaths === 'string') {
fabric.loadSVGFromURL(originalPaths, function (elements) {
var pathUrl = originalPaths;
var group = fabric.util.groupSVGElements(elements, object, pathUrl);
object.paths = originalPaths;
callback(group);
});
}
else {
fabric.util.enlivenObjects(originalPaths, function(enlivenedObjects) {
enlivenedObjects.forEach(function(obj) {
obj._removeTransformMatrix();
})
var group = new fabric.Group(enlivenedObjects, object);
object.paths = originalPaths;
callback(group);
});
}
};
});
/** ---------------------------------------------------------------------------*/
/** CHANGE MATERIAL JS (JS ONLY) */
/** ---------------------------------------------------------------------------*/
function changeMaterialJS(matid,prodid,jsondata)
{
handleInputs('disable');
// APPLY NAV
$('.panelMaterial').each(function() { $(this).removeClass('gradSelect'); });
$("#MATNAVID"+matid).addClass('gradSelect');
// DESELECT ALL
canvas.discardActiveObject();
// GET JSON
var SHIELD = JSON.parse(SCONFIG);
// GET MATERIAL + PRODUCT
var MAT = SHIELD[matid];
var PROD = new Object();
$.each(MAT['PRODUCTS'],function(index, value){
if(value['PID']==prodid) { PROD = MAT['PRODUCTS'][index]; }
});
$('#MATERIALID').val(matid);
$('#MATERIALNAME').val(MAT['MNAME']);
$('#MATERIALDISPLAY').html(MAT['MNAME']); // For Display in green bar
$('#PRODUCTID').val(prodid);
$('#PRODUCTNAME').val(PROD['PNAME']);
LOG && console.log(MAT);
LOG && console.log(PROD);
// ENABLE/DISABLE CUTFORMS
switch(MAT['MCUTFORM'])
{
case '1': $('#CUTFORMDISPLAY').show(); break;
default: $('#CUTFORMDISPLAY').hide();
}
// RESTORE STAERKE
var STAERKE_CUR = $('#STAERKE option:selected').val();
var STAERKE_EXIST=0; var STAERKE_DEF='';
var STAERKE_DIS='';
$('#STAERKE').empty();
$.each(MAT['PRODUCTS'],function(index, value) {
if(value['PID']==STAERKE_CUR) { STAERKE_EXIST=1; }
if(value['PDEFAULT']==1) { STAERKE_DEF = value['PID']; }
//STAERKE_DIS= value['PSTAERKE'].replace('.',',').slice(0,-1);
STAERKE_DIS= value['PSTAERKE'];
$('#STAERKE').append($("").attr("value", value['PID']).text(STAERKE_DIS+' mm'));
});
//if(STAERKE_EXIST==0) { $('#STAERKE option[value="'+STAERKE_DEF+'"]').attr('selected', true); }
//else { $('#STAERKE option[value="'+STAERKE_CUR+'"]').attr('selected', true); }
if(STAERKE_EXIST==0) { $('#STAERKE option[value="'+STAERKE_DEF+'"]').prop('selected', true); }
else { $('#STAERKE option[value="'+STAERKE_CUR+'"]').prop('selected', true); }
// RESTORE STAERKE
$('#wkStaerke').html($('#STAERKE option:selected').text());
// RESTORE ENGRAVEMETHOD
var CURRENTEMID = $('#ENGRAVEMETHOD option:selected').val();
var CURRENTENGRAVEMINFONTSIZE= $('#ENGRAVEMINFONTSIZE').val();
var CURRENTENGRAVEFILLABLE= $('#ENGRAVEFILLABLE').val();
var EMDEFAULT=''; var ENGRAVEMINFONTSIZEDEFAULT=''; var ENGRAVEFILLABLEDEFAULT= ''; var EMIDEXISTS=0;
$('#ENGRAVEMETHOD').empty();
$.each(PROD['ENGRAVE_METHODS'],function(index, value) {
if(value['EMID']==CURRENTEMID) { EMIDEXISTS=1; $('#ENGRAVEMINFONTSIZE').val(value['EMMINFONTSIZE']); $('#ENGRAVEFILLABLE').val(value['AUSLEGBAR_MF']); }
if(value['PEMDEFAULT']==1) { EMDEFAULT = value['EMID']; ENGRAVEMINFONTSIZEDEFAULT= value['EMMINFONTSIZE']; ENGRAVEFILLABLEDEFAULT=value['AUSLEGBAR_MF']; }
$('#ENGRAVEMETHOD').append($("").attr("value", value['EMID']).text(value['EMNAME']));
});
if(EMIDEXISTS==0) { $('#ENGRAVEMETHOD option[value="'+EMDEFAULT+'"]').prop('selected', true); $('#ENGRAVEMINFONTSIZE').val(ENGRAVEMINFONTSIZEDEFAULT); $('#ENGRAVEFILLABLE').val(ENGRAVEFILLABLEDEFAULT); }
else { $('#ENGRAVEMETHOD option[value="'+CURRENTEMID+'"]').prop('selected', true); }
// RESTORE FRAESGRAVUREN SETTINGS + COLOR PANEL
if($('#ENGRAVEMETHOD option:selected').val()==999) // NEEDED 3 TO DEAVTICA FRAES
{
$('#TOBASKETAREA').hide();
$('#ORAREA').hide();
$('#ANFRAGEAREA').show();
$('#ANFRAGEAREANETTO').show();
$('#ANFRAGEAREAJS').show();
$('#wkPrice').hide();
$('#wkPriceNetto').hide();
$('#wkPriceJS').hide();
//$('#JSPRICEAREANETTO').hide();
//$('#JSPRICEAREA').hide();
$('#anfrageWindow').text('Anfrage stellen');
}
else
{
$('#TOBASKETAREA').show();
$('#ORAREA').show();
$('#ANFRAGEAREA').hide();
$('#ANFRAGEAREANETTO').hide();
$('#ANFRAGEAREAJS').hide();
$('#wkPrice').show();
$('#wkPriceNetto').show();
$('#wkPriceJS').show();
//$('#JSPRICEAREANETTO').show();
//$('#JSPRICEAREA').show();
$('#anfrageWindow').text('A');
}
$('#ENGRAVEFILLABLE').val()==1 ? $('#objFillColorPanel').show() : $('#objFillColorPanel').hide();
// RESTORE SIGN SIZE // SIGN STD / DIMS
var CURRENTDIMMODE = $("input[name=DIMMODE]:checked").val(); //$('#DIMMODE').val();
var CURRENTDIMSTD = $('#DIMSTD').val(); //$('#DIMSTD option:selected').val();
var CURRENTDIMFREE = $('#DIMFREE').val();
var CURRENTWIDTH = $('#WIDTH').val();
var CURRENTHEIGHT = $('#HEIGHT').val();
LOG && console.log('CURRENTDIMSTD: '+ CURRENTDIMSTD +', CURRENTDIMMODE: '+ CURRENTDIMMODE+', CURRENTDIMFREE: '+ CURRENTDIMFREE +', CURRENTWIDTH: '+ CURRENTWIDTH +', CURRENTHEIGHT: '+ CURRENTHEIGHT);
// RESTORE DIM DEFAULTS IF DOESN'T EXISTS
var SIGNDIMEXISTS=0; var SIGNDIMDEFAULT='';
$('#DIMSTD').empty();
$.each(MAT['SIGN_DIM'],function(index, value){
if(CURRENTDIMSTD==value['DIMX']+'x'+value['DIMY']) { SIGNDIMEXISTS=1; }
if(value['DIMDEFAULT']==1) { SIGNDIMDEFAULT= value['DIMX']+'x'+value['DIMY']; }
$('#DIMSTD').append($("").attr("value", value['DIMX']+'x'+value['DIMY']).text(value['DIMX']+' x '+value['DIMY']+' mm'));
});
if(PROD['PDIMFREE']==1)
{
if(SIGNDIMEXISTS==0) // && CURRENTDIMMODE==1)
{
switch(CURRENTDIMMODE)
{
case '1':
$("#DIMMODE1").prop("checked", true);
break;
default:
$("#DIMMODE1").prop("checked", true);
var dim =CURRENTDIMSTD.split('x');
$('#WIDTH').val(dim[0]);
$('#HEIGHT').val(dim[1]);
}
}
else
{
switch(CURRENTDIMMODE)
{
case '1':
$("#DIMMODE1").prop("checked", true);
$('#WIDTH').val(CURRENTWIDTH);
$('#HEIGHT').val(CURRENTHEIGHT);
break;
default:
$("#DIMMODE1").prop("checked", true);
$('#WIDTH').val(CURRENTWIDTH);
$('#HEIGHT').val(CURRENTHEIGHT);
}
}
}
else
{
$("#DIMMODE0").prop("checked", true);
$('#DIMSTD option[value="'+SIGNDIMDEFAULT+'"]').prop('selected', true)
var dim =SIGNDIMDEFAULT.split('x');
$('#WIDTH').val(dim[0]);
$('#HEIGHT').val(dim[1])
}
// SET DIMFREE SELECTOR
switch(PROD['PDIMFREE'])
{
case '1': $('#DIMFREEDISPLAY').show(); break;
default: $('#DIMFREEDISPLAY').hide();
}
$('#DIMFREE').val(PROD['PDIMFREE']);
// DISPLAY MESSAGE FOR RONDEN / OVALE
switch(PROD['PID'])
{
case '15':
case '16': $('#OVALEDISPLAY').show(); $('#RONDENDISPLAY').hide(); break;
case '17':
case '18': $('#RONDENDISPLAY').show(); $('#OVALEDISPLAY').hide(); break;
default: $('#OVALEDISPLAY').hide(); $('#RONDENDISPLAY').hide();
}
// RESTORE SIGN FORMS + BORDER
var CUR_FORMID = $('#FORMID').val();
var CUR_FORM = $('#FORM').val();
var CUR_FORMDATA = $('#FORMDATA').val();
var CUR_BORDERID = $('#BORDERID').val();
var CUR_BORDERDATA = ''; //$('#BORDERID').val();
var FORMIDEXISTS=0; var FORMID_DEF=''; var FORM_DEF=''; var FORMDATA_DEF=''; var BORDERIDEXISTS=0; var BORDERID_DEF=''; var BORDERDATA_DEF='';
LOG && console.log('CUR_FORMID: '+ CUR_FORMID +', CUR_FORM: '+ CUR_FORM+', CUR_FORMDATA: '+ CUR_FORMDATA +', CUR_BORDERID: '+ CUR_BORDERID);
// FORMS
$('#SLIDERFORMS').empty();
$.each(PROD['SIGN_FORMS'],function(index, value)
{
if(value['SFDEFAULT']==1)
{
FORMID_DEF = value['SFID'];
FORM_DEF = value['SFNAME'];
FORMDATA_DEF = value['SFDATA'];
}
var currentPanel= xs==2 ? 'panelThirdClose':'panelThird';
if(value['SFID']==CUR_FORMID) { FORMIDEXISTS=1; }
$('#SLIDERFORMS').append("\n");
xs++;
if(xs==3) { $('#SLIDERFORMS').append('\n'); xs=0; }
});
if(xs!=3 && xs!=0) { $('#SLIDERFORMS').append('
\n'); }
if(FORMIDEXISTS==0) { $('#FORMID').val(FORMID_DEF); $('#FORM').val(FORM_DEF); $('#FORMDATA').val(FORMDATA_DEF); }
else { $('#FORMID').val(CUR_FORMID); $('#FORM').val(CUR_FORM); $('#FORMDATA').val(CUR_FORMDATA); }
// BORDERS
$('#SLIDERBORDERS').empty();
$.each(PROD['SIGN_BORDERS'],function(index, value)
{
if(value['SBDEFAULT']==1)
{
BORDERID_DEF=value['SBID'];
BORDERDATA_DEF=value['SBDATA'];
}
var currentPanel= xs==2 ? 'panelThirdClose':'panelThird';
if(value['SBID']==CUR_BORDERID) { BORDERIDEXISTS=1; }
$('#SLIDERBORDERS').append("\n");
xs++;
if(xs==3) { $('#SLIDERBORDERS').append('\n'); xs=0; }
});
if(xs!=3 && xs!=0) { $('#SLIDERBORDERS').append('
\n'); }
if(BORDERIDEXISTS==0) { $('#BORDERID').val(BORDERID_DEF); $('#BORDERDATA').val(BORDERDATA_DEF); }
else { $('#BORDERID').val(CUR_BORDERID); $('#BORDERDATA').val(CUR_BORDERDATA); }
// RESTORE COLORS
/** NEW RESTORE **/
var CUR_COLORID = $('#COLORID').val();
var CUR_COLORNAME = $('#COLORNAME').val();
var CUR_COLORGROUPID = $('#COLORGROUPID').val();
var CUR_COLOR = $('#COLOR').val();
var CUR_COLORBG = $('#COLORBG').val();
var CUR_COLORBGIMAGE = $('#COLORBGIMAGE').val();
var CUR_COLORPRICE = $('#COLORPRICE').val();
var x=0; var xs=0; var xrow=0; var colorName=''; var colorDisplay=''; var VERWENDUNG=''; var LIEFERZEIT=''; var bgdisplay=''; var COLAPPEND=''; var padding=0; var OLDSTAERKE='';
var COLORGROUPIDEXISTS=0; var COLORID_DEF=''; var COLORNAME_DEF=''; var COLORGROUPID_DEF=''; var COLOR_DEF=''; var COLORBG_DEF=''; var COLORBGIMAGE_DEF='';
$('#SLIDERCOLORS').empty();
$.each(MAT['PRODUCTS'],function(pindex, pvalue)
{
var PIDCOLORS = pvalue['COLORS'];
var EMETHODS = pvalue['ENGRAVE_METHODS'];
x=0;
$.each(PIDCOLORS,function(index, value)
{
// if(value['CGID']==CUR_COLORGROUPID) { COLORGROUPIDEXISTS=1; CUR_COLORID=value['CID'] }
if(CUR_COLORID==value['CID'] && pvalue['PID']==prodid) { COLORGROUPIDEXISTS=1; CUR_COLORID=value['CID'] }
//console.log('STAERKE/PID :' + pvalue['PID'] + ', '+prodid+ '|' + CUR_COLORID + ', ' + value['CID'] + '| COLORGROUPEXISTS?: ' + COLORGROUPIDEXISTS);
if(value['CGBGIMAGE'].length==0) { value['CGBGIMAGE']=''; } else { value['CGBGIMAGE']='../' + value['CGBGIMAGE']; }
if(x==0 && pvalue['PID']==prodid)
{
COLORID_DEF=value['CID'];
COLORNAME_DEF=value['CGNAME'];
COLORGROUPID_DEF=value['CGID'];
COLOR_DEF=value['CGCOLOR'];
COLORBG_DEF= value['CGBGCOLOR'];
COLORBGIMAGE_DEF = value['CGBGIMAGE'];
COLORPRICE_DEF=value['CPA'];
}
colorName = value['CGNAME'];
colorDisplay = value['CGNAME'].replace('/','
');
if(value['CLIEFERZEIT']!=0) { LIEFERZEIT=value['CLIEFERZEIT']+' Werktage'; } else { LIEFERZEIT='sofort lieferbar'; }
switch(value['CVERWENDUNG'])
{
case '1': VERWENDUNG='nur Aussen verwendbar'; break;
case '2': VERWENDUNG='Innen und Aussen verwendbar'; break;
default: VERWENDUNG='nur Innen verwendbar';
}
if(value['CUVRESISTENT']==1) { VERWENDUNG = VERWENDUNG + ", UV-Resistent"; }
/** SPLIT COLORS **/
// if(OLDSTAERKE!=pvalue['PSTAERKE'] && xrow>0) { padding='25px'; OLDSTAERKE=pvalue['PSTAERKE']; $('#SLIDERCOLORS').append(COLAPPEND + '
'); xs=0; }
// var currentPanel= xs==2 ? 'colorThirdClose':'colorThird';
var currentPanel= 'colorThird';
if(xs==0) { COLAPPEND=''; }
bgdisplay = value['CGBGIMAGE'].length > 0 ? "background: url("+value['CGBGIMAGE']+")" : "background: "+value['CGBGCOLOR']+"";
bgimage = value['CGBGIMAGE'].length > 0 ? value['CGBGIMAGE'] : '';
pdisplay=pvalue['PSTAERKE'].replace('.',',');
if(pvalue['PID']==$('#PRODUCTID').val())
{
$.each(EMETHODS,function(emindex, emvalue)
{
COLAPPEND = COLAPPEND + "
\n";
});
}
else
{
$.each(EMETHODS,function(emindex, emvalue)
{
COLAPPEND = COLAPPEND + "
\n";
});
}
xs++;
if(xs==3) { COLAPPEND=COLAPPEND + ' \n'; xs=0; $('#SLIDERCOLORS').append(COLAPPEND); COLAPPEND=''; }
x++;
});
xrow++;
});
if(xs!=3 && xs!=0) { COLAPPEND= COLAPPEND + '
\n'; $('#SLIDERCOLORS').append(COLAPPEND); }
if(COLORGROUPIDEXISTS==0) { $('#COLORID').val(COLORID_DEF); $('#COLORNAME').val(COLORNAME_DEF); $('#COLORGROUPID').val(COLORGROUPID_DEF); $('#COLOR').val(COLOR_DEF); $('#COLORBG').val(COLORBG_DEF); $('#COLORBGIMAGE').val(COLORBGIMAGE_DEF); $('#COLORPRICE').val(COLORPRICE_DEF); }
else { $('#COLORID').val(CUR_COLORID); $('#COLORNAME').val(CUR_COLORNAME); $('#COLORGROUPID').val(CUR_COLORGROUPID); $('#COLOR').val(CUR_COLOR); $('#COLORBG').val(CUR_COLORBG); $('#COLORBGIMAGE').val(CUR_COLORBGIMAGE); $('#COLORPRICE').val(CUR_COLORPRICE); }
// RESTORE DIMMAX, DIMMIN
var PDIMMAX = PROD['PMAXX']+'x'+PROD['PMAXY'];
var PDIMMIN = PROD['PMINX']+'x'+PROD['PMINY'];
$('#DIMMAX').val(PDIMMAX);
$('#DIMMIN').val(PDIMMIN);
// RESTORE FIXATIONDATA
var CUR_FIXATIONID = $('#FIXATIONID').val();
var CUR_FIXATIONNAME = $('#FIXATIONNAME').val();
var x=0; var xs=0; var dpimage = ''; var FIXAPPEND=''; var settableFixations = ['2','3','4','8','10','11'];
var FIXATIONIDEXISTS=0; var FIXATIONID_DEF=''; var FIXATIONNAME_DEF=''; var FIXATIONDATA=''; var FIXATIONID_DEF=1; var FIXATIONNAME_DEF='Keine';
$('#SLIDERFIXATIONS').empty();
// GET CURRENT FIXATIONS
var SIGN_FORMS = new Object(); var TMP_SIGN_FORMS = new Object();
$.each(PROD['SIGN_FORMS'],function(index, value)
{
if(value['SFID']==$('#FORMID').val()) { SIGN_FORMS = PROD['SIGN_FORMS'][index]; }
TMP_SIGN_FORMS = PROD['SIGN_FORMS'][index];
/* INVALID JQUERY 2.4 */
//console.log(TMP_SIGN_FORMS)
//if(TMP_SIGN_FORMS['SFFIXATIONS']!==null)
if(TMP_SIGN_FORMS['SFFIXATIONS'].length > 0)
{
//console.log('bigger than none');
$.each(TMP_SIGN_FORMS['SFFIXATIONS'],function(index, value)
{
// ALL FIXATIONDATA NEEDED
//if(value['DISTANCE']===null) { value['DISTANCE']=''; }
FIXATIONDATA = FIXATIONDATA + value['SFID'] +','+value['FXID']+','+ value['MINWIDTH']+','+value['MINHEIGHT']+','+value['DISTANCE']+'###';
});
}
});
FIXAPPEND = "
";
if(SIGN_FORMS['SFFIXATIONS'].length > 0)
{
$.each(SIGN_FORMS['SFFIXATIONS'],function(index, value)
{
if(value['FXID']==CUR_FIXATIONID) { FIXATIONIDEXISTS=1; CUR_FIXATIONID=value['FXID'] }
switch(value['FXID'])
{
case '7' : dpimage='ws'; break;
case '23': dpimage='wsgold'; break;
case '26': dpimage='wsgold'; break;
case '9' : dpimage='screw'; break;
default : dpimage=''; break;
}
var FXDETAILS ='';
var DATASETFX =0;
//console.log(value['FXFILEDESC'] +', '+value['FXDESC']);
if(value['FXFILEDESC'].length > 0 || value['FXDESC'].length > 0)
{ value['FXFILEDESC'] = value['FXFILEDESC'].length > 0 ? '../../xkonf/fixations/' + value['FXFILEDESC'] : '';
//FXDETAILS = "";
FXDETAILS='Details';
}
if(settableFixations.includes(value['FXID']))
{
FXDETAILS = FXDETAILS.length > 0 ? FXDETAILS + ' / Abstand einstellen' : 'Abstand einstellen';
DATASETFX=1;
}
FIXAPPEND = FIXAPPEND + "
";
});
}
$('#SLIDERFIXATIONS').append(FIXAPPEND); // + '\n');
if(FIXATIONIDEXISTS==0) { $('#FIXATIONID').val(FIXATIONID_DEF); $('#FIXATIONNAME').val(FIXATIONNAME_DEF); }
else { $('#FIXATIONID').val(CUR_FIXATIONID); $('#FIXATIONNAME').val(CUR_FIXATIONNAME); }
// RESTORE COMPONENTS
var COMPONENTSAPPEND = '';
$('#SLIDERCOMPONENTS').empty();
$.each(PROD['COMPONENTS'],function(index, value)
{
//console.log($('#componentsDesc'+value['CPID']).html());
var COMPONENTDATA = $('#componentsDesc'+value['CPID']).html().length > 0 ? "Details
":"";
COMPONENTSAPPEND = COMPONENTSAPPEND + ""+value['CPNAME']+"
" + COMPONENTDATA + "
";
});
$('#SLIDERCOMPONENTS').append(COMPONENTSAPPEND); // + '\n');
// INITIZALIE NEW CONFIGURATOR
LOG && console.log('%cinitConfSign(\''+$("input[name=DIMMODE]:checked").val()+'\',\''+$('#DIMFREE').val()+'\',\''+$('#DIMSTD').val()+'\',\''+$('#WIDTH').val()+'\',\''+$('#HEIGHT').val()+'\',\''+$('#COLOR').val()+'\',\''+$('#COLORBG').val()+'\',\''+$('#COLORBGIMAGE').val()+'\',\''+$('#COLORNAME').val()+'\',\''+$('#COLORID').val()+'\',\''+$('#COLORGROUPID').val()+'\',\''+$('#FORM').val()+'\',\''+$('#FORMDATA').val()+'\',\''+$('#FORMID').val()+'\',\'border\',\''+$('#BORDERID').val()+'\',\''+PDIMMAX+'\',\''+PDIMMIN+'\',\''+$('#TXTMODE').val()+'\',\''+FIXATIONDATA+'\',\''+MAT['MCUTFORM']+'\',\''+jsondata+'\',\'1\')',"color: white; background-color: black; padding: 4px");
initConfSign($("input[name=DIMMODE]:checked").val(),$('#DIMFREE').val(),$('#DIMSTD').val(),$('#WIDTH').val(),$('#HEIGHT').val(),$('#COLOR').val(),$('#COLORBG').val(),$('#COLORBGIMAGE').val(),$('#COLORNAME').val(),$('#COLORID').val(),$('#COLORGROUPID').val(),$('#FORM').val(),$('#FORMDATA').val(),$('#FORMID').val(),'border',$('#BORDERID').val(),PDIMMAX,PDIMMIN,$('#TXTMODE').val(),FIXATIONDATA,MAT['MCUTFORM'],jsondata,'1');
//initConfSign($('#DIMMODE').val(),$("#DIMFREE").val(),'{$_SESSION['SIGN']['DIMSTD']}','{$_SESSION['SIGN']['WIDTH']}','{$_SESSION['SIGN']['HEIGHT']}','{$_SESSION['SIGN']['COLOR']}','{$_SESSION['SIGN']['COLORBG']}','{$_SESSION['SIGN']['COLORBGIMAGE']}','{$_SESSION['SIGN']['COLORNAME']}','{$_SESSION['SIGN']['COLORID']}','{$_SESSION['SIGN']['COLORGROUPID']}','{$_SESSION['SIGN']['FORM']}','{$_SESSION['SIGN']['FORMDATA']}','{$_SESSION['SIGN']['FORMID']}','{$_SESSION['SIGN']['BORDER']}','{$_SESSION['SIGN']['BORDERID']}','{$_SESSION['SIGN']['DIMMAX']}','{$_SESSION['SIGN']['DIMMIN']}','{$_SESSION['SIGN']['TXTMODE']}','{$_SESSION['SIGN']['FIXATIONDATA']}','{$_SESSION['SIGN']['CUTFORMSENABLED']}','$JSONFILE');
$('#CONTAINERCURRENTJSVAL').html(
''+
'MATERIALID: | '+ $('#MATERIALID').val() + ' |
' +
'PRODUCTID: | '+ $('#PRODUCTID').val() + ' |
' +
'STAERKE: | '+ $('#STAERKE').val() + ' |
' +
'ENGRAVEMETHOD: | '+ $('#ENGRAVEMETHOD').val() + ' |
' +
'
'
);
if(SIGN.closeMenuAfterAdd===true) { closeMenues(); }
handleInputs('enable');
return false;
}
/** ---------------------------------------------------------------------------*/
/** INIT SIGN (JS + PHP) */
/** ---------------------------------------------------------------------------*/
function initConfSign(dimmode,dimfree,dimstd,x,y,col,bgcol,bgimage,colname,colid,colgroupid,sform,sformdata,sformid,border,borderid,dimmax,dimmin,textmode,fixationdata,cutformsenabled,json,reloadFromJS)
{
if(reloadFromJS!=1) { canvas.clear(); }
LOG && console.log('ReloadFromJS: ' +reloadFromJS)
//-->
handleInputs('disable');
$('#schild').hide();
SIGN.width=x;
SIGN.height=y;
SIGN.color = col;
SIGN.bgcolor = bgcol;
SIGN.dimMax=dimmax;
SIGN.dimMin=dimmin;
FIXDATA = new Array(); // RESET GLOBAL FIXDATA
ROWS = fixationdata.split('###');
ROWS.forEach(function(entry) {
dataentry=entry.split(',');
if(entry.length > 0) { FIXDATA.push(dataentry); }
});
//alert(FIXDATA.length);
var max = SIGN.dimMax.split('x');
var min = SIGN.dimMin.split('x');
if(textmode==1) // SERIENTEXT
{
$('#serientext').show();
$('#TXTMODE').val(1);
$('#MENGE').val()==1 ? $('#stSignDisplay').text($('#MENGE').val()+ ' Entwurf') : $('#stSignDisplay').text($('#MENGE').val()+ ' Entw\u00fcrfe');
$('#MENGE').prop('readonly', true);
}
$('#WIDTH').val(SIGN.width)
$('#HEIGHT').val(SIGN.height)
if(json.length > 0)
{
//console.log(json)
json = json.replace(/'/g,"\'");
//json = json.replace(/\"/g,'\\"');
json = json.replace(/\n/g, "\\n");
json = json.replace(/\r/g, "\\r");
json = json.replace(/\t/g, "\\t");
json = json.replace(/\f/g, "\\f");
//json = json.replace(/\/g, "\\");
//json = filterUCChars($(this).val(),obj.get('text'));
LOG && console.log('initSign from JSON (PHP)');
//console.log(json);
//var start = timer(0);
// canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
// var start = timer(0);
// var tdiff = timer(start);
// LOG && console.log(o,object); // 'Object loaded in: ' +tdiff + ', Object:' + fabric.log(o, object));
// });
/* GET SCALE DIM */
var xRatio = parseFloat(SIGN.maxWidth/x);
var yRatio = parseFloat(SIGN.maxHeight/y); //.toPrecision(5);
SIGN.scaleFac = x > y && (xRatio*y) < SIGN.maxHeight ? xRatio : yRatio;
var leftPos = ($('#canvasBox').width() - SIGN.width * SIGN.scaleFac)/2;
var topPos = ($('#canvasBox').height() - SIGN.height * SIGN.scaleFac)/2;
LOG && console.log('SignLeftTop X,Y: ' + leftPos + ',' + topPos + ', SC :' +SIGN.scaleFac);
/* CHECK FOR OLD TEMPLATES */
if($('#OLDTEMPLATE').val()==1) { SIGN.oldTemplate=true; }
var objCount=0;
canvas.loadFromJSON(json, function ()
{
if(SIGN.oldTemplate)
{
console.log('trying to correct old sign template');
canvas.forEachObject(function(o)
{
if(objCount>1)
{
console.log(o);
//console.log('LEFT/RIGHT: ' + leftPos + ',' +topPos + ', OBJECT: ' + o.left +','+o.top+',' +o.scaleX);
if(o.mmkLayerType=='layerFixation') { }
else
{
//$('#objXPos').val(parseFloat((obj.get('left') / SIGN.scaleFac) - (canvas.item(0).get('left') / SIGN.scaleFac)).toFixed(1));
//$('#objYPos').val(parseFloat((obj.get('top') / SIGN.scaleFac) - (canvas.item(0).get('top') / SIGN.scaleFac)).toFixed(1));
objX = o.left * o.scaleX; ///o.scaleX;
objY = o.top * o.ScaleY; ///o.scaleY;
//console.log('OBJ X/Y: ' +o.type + ': ' + objX +','+objY);
newLeft = leftPos + o.left /o.scaleX;
newTop = topPos + o.top/o.scaleY;
//formatObjControls(canvas.item(x),1);
//console.log('OLDPOS_LEFT: ' + o.left + ' OLD_SCALEX: '+ o.scaleX + ', SIGNPOS_LEFT: ' +leftPos + ', ENDPOS_LEFT: ' +newLeft );
//console.log('OLDPOS_TOP: ' + o.top + ' OLD_SCALEY: '+ o.scaleY + ', SIGNPOS_TOP: ' +topPos + ', ENDPOS_TOP: ' +newTop);
o.set('left',newLeft);
o.set('top',newTop);
o.setCoords();
}
}
objCount++;
});
canvas.renderAll();
SIGN.oldTemplate=false; // RESET
$('#OLDTEMPLATE').val('');
}
//var tdiff = timer(start);
//LOG && console.log('JSON loads in: ' +tdiff);
//canvas.loadFromDatalessJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
// fabric.log(o, object);
//});
});
canvas.calcOffset();
canvas.renderAll();
}
else
{
LOG && console.log('init from JS');
//LOG && fabric.log(o, object);
}
var removeCFID=new Array();
var oldbgObj = new Array();
delay(async function() { // CAUSE IMAGES IN JSON ARE NOT LOADED PROPERLY
var startdelay = timer(0);
//console.log('INITIALIZE OBJECTS FROM LOADER');
//console.log('Background: ' +bgimage+ ', ReloadFromJS: ' + reloadFromJS)
if(bgimage.match(/^\.\.\/xkonf\/.*/)) { bgimage = '../'+bgimage; $('#COLORBGIMAGE').val(bgimage); }
//console.log('BackgroundAfter: ' +bgimage+ ', ReloadFromJS: ' + reloadFromJS)
for(x=2; x < canvas.getObjects().length; x++)
{
obj = canvas.item(x);
formatObjControls(obj,1);
if(obj.mmkLayerType=='layerCutForm' && cutformsenabled==0) { removeCFID.push(x); }
if(obj.mmkRenderAsCutForm && cutformsenabled==0) { removeCFID.push(x); }
if(obj.mmkLayerType=='layerFixation') { oldbgObj.push(obj); }
var start = timer(0);
LOG && console.log(obj);
var tdiff = timer(start);
LOG && console.log('Applying Image Filters in: ' +tdiff);
if(obj.get('type')=='i-text')
{
//console.log('Font in Template:')
//console.log(obj.fontFamily);
fabric.util.clearFabricFontCache(); // fixed nasty recalc error
var fontFound = 0;
var templateFont = obj.fontFamily;
for (var key in SIGN.vectorizableFonts) { if(templateFont == SIGN.vectorizableFonts[key]['cssName']) { fontFound=1; break; }}
if(fontFound ==0 ) { for (var key in SIGN.nonVectorizableFonts) { if(templateFont == key) { fontFound=1; break; }}}
if(fontFound==0) {
obj.set({'fontFamily': SIGN.defaultFont, 'fontWeight':'normal', 'fontStyle':'normal'});
await vectorizeFont(obj,'obj_modified',obj.type);
}
}
}
/* REMOVE CUTFORMS IF CUTFORMSENABLED=0; */
for(var x = removeCFID.length; x--;)
{
fx=removeCFID[x];
canvas.remove(canvas.item(fx));
}
/* SET SIGN STATE */
createBackgroundArea(sform,sformdata,sformid,border,borderid,0);
changeBackColor('',col,bgcol,colname,colid,bgimage,colgroupid,0);
resizeBack(SIGN.width,SIGN.height);
refreshMiniView('initConfSign');
/* TRY TO RESTORE FIXATIONS BY OLD BG */
if(json.length > 0) { restoreFixationByJSON(oldbgObj); }
setCanvasZoomInit('initConfSign');
canvas.renderAll();
$('#schild').show();
var tdiffdelay = timer(startdelay);
LOG && console.log('Delayed Object Loader in initConfSign() (150 ms) loads in: ' +tdiffdelay);
}, 225); // 150
//calculateSign('initConfSign',0);
handleInputs('enable');
}
/** ---------------------------------------------------------------------------*/
/** CALCULATE SIGN (PHP MODE + JS ONLY MODE) */
/** ---------------------------------------------------------------------------*/
async function calculateSign(source,type)
{
handleInputs('disable');
var typeval=new Array('JS ONLY','PHP + JS');
var autoSet=0;
if(type==null) { type=0; autoSet=1; } // TYPE NOT SET IN FUNCTIONS
// CHECK FOR SELECTED I-TEXT ... VECTORIZE BEFORE CALC
var obj = canvas.getActiveObject();
if(obj && obj.mmkLayerType=='layerVectorEditor' && (source=='addSignToBasket' || source=='saveTempSVG' || source=='createAngebot' || source=='prepareAnfrage'))
{
//console.log(source + ', starte calculate Sign');
await vectorizeFont(obj,'obj_modified',obj.type);
//canvas.discardActiveObject();
}
if(PHPCALC==true) { type=1; autoSet=1; } // ENABLES PHP MODE ALWAYS (GLOBAL)
LOG && console.log('%cCalculatingSign: Source: '+source+', Mode: '+typeval[type]+', Autoset: ' + autoSet + ', PHPCALCMODE: ' + PHPCALC,"color:white; background: #cc0000; padding:4px;");
// TIME
var start = timer(0);
// GRAVURFLAECHE ERMITTELN
var gFull = 0;
var sFull = 0;
var gColorArea = new Object();
var gColorList = [];
var gColorRoam = '';
var gAll = 0;
var sAll = 0;
var bildmontage= 0;
var staerke = $('#STAERKE option:selected').text()
staerke = staerke.replace("mm",'');
staerke = parseFloat(staerke.replace(",",'.')).toFixed(2);
var fixHoleData= {'fixMode':$('#fixEditMode').val(), 'fixDiameter':$('#fixDiameter').val(), 'fixVertikal1': $('#fixVertikal1').val(), 'fixHorizontal2': $('#fixHorizontal2').val(), 'fixHorizontal4': $('#fixHorizontal4').val(), 'fixVertikal4': $('#fixVertikal4').val()};
// BORDER?
var xs=2;
if($('#BORDERID').val()==2) { xs=1; } // Thin
if($('#BORDERID').val()==3) { xs=1; } // Thick
for(let x = xs; x < canvas.getObjects().length; x++)
{
if(canvas.item(x).type=='image' || canvas.item(x).type=='path' || canvas.item(x).type=='group' || canvas.item(x).type=='path-group' || canvas.item(x).type=='i-text' || canvas.item(x).type=='circle' || canvas.item(x).type=='rect' || canvas.item(x).type=='triangle' || canvas.item(x).type=='polygon')
{
gwidth = ((canvas.item(x).get('width')*canvas.item(x).scaleX)/10) / SIGN.scaleFac;
gheight = ((canvas.item(x).get('height')*canvas.item(x).scaleY)/10) / SIGN.scaleFac;
}
else
{
gwidth = (canvas.item(x).get('width')/10) /SIGN.scaleFac;
gheight = (canvas.item(x).get('height')/10)/SIGN.scaleFac;
}
//LOG && console.log('Type:' + canvas.item(x).type + ',' +gwidth + ' x ' +gheight+ ',Scale: ' + canvas.item(x).scaleX + ',' +canvas.item(x).scaleY);
gAll = gwidth * gheight;
sAll = gwidth * 2 + gheight * 2;
/** DO NOT CALC EDITORS FOR VECTORIZING TWICE */
if(canvas.item(x).mmkLayerType=='layerVectorEditor')
{
gAll = 0;
sAll = 0;
}
/** Gravurflaeche oder Ausschnittflache */
//console.log('nicht synchron');
//console.log(canvas.item(x));
if(canvas.item(x).mmkLayerType=='layerCutForm' || (canvas.item(x).mmkRenderAsCutForm && canvas.item(x).type == 'group'))
{
if(canvas.item(x).mmkRenderAsCutForm && canvas.item(x).type=='group')
{
//console.log('Calculating Path Length for Textausschnitte');
var pathLength = 0;
var group = canvas.item(x);
for (var i=0; i < group.getObjects().length; i++)
{
var pathInfo = fabric.util.getPathSegmentsInfo(group.item(i).path);
var segmentLength = (pathInfo[pathInfo.length - 1].length / 10 / SIGN.scaleFac) * group.scaleX;
//console.log('Länge Ausschnitt: ' + segmentLength + ' cm');
pathLength+= segmentLength;
}
//console.log('Länge Ausschnitt Gesamt: ' + pathLength + ' cm');
sFull+=pathLength;
}
else
{
sFull+= sAll;
}
/* BERECHNE PFADLAENGE - NICHT KOMPLETT, FORMEN FEHLEN (DISABLED)
//let type = canvas.item(x).get('type');
//console.log('Cutform (Classic) -> ' + type +' : ' + sAll + ' cm');
//console.log(canvas.item(x).get('type'));
let realLength = 0;
switch(canvas.item(x).type)
{
case 'rect': realLength = sAll; break;
case 'ellipse':
case 'circle': var rx = gwidth/2; var ry = gheight/2; realLength = Math.PI * Math.sqrt(2 * (Math.pow(rx,2) + Math.pow(ry,2))); break;
case 'triangle': console.log(canvas.item(x)); break;
case 'path': console.log(canvas.item(x));
//realLength = canvas.item(x).get('path').getTotalLength();
var pathInfo = fabric.util.getPathSegmentsInfo(canvas.item(x).path);
console.log(pathInfo[pathInfo.length - 1].length);
realLength = (pathInfo[pathInfo.length - 1].length / 10 / SIGN.scaleFac) * canvas.item(x).scaleX;
console.log('ScaleFac:' + SIGN.scaleFac);
break;
}
console.log('Cutform (Classic vs RealLength) -> ' + canvas.item(x).type +' : ' + sAll + ' vs ' + realLength + ' cm');
*/
}
else
{
gFull+= gAll;
}
// FARBAUSLAGE BERECHNEN
if(canvas.item(x).mmkLayerFill == 1 && canvas.item(x).mmkLayerType!='layerVectorEditor') //Type=='layerFillColor')
{
switch(canvas.item(x).type)
{
case 'i-text':
if(canvas.item(x).get('text').trim().length > 0 && canvas.item(x).mmkLayerType!='layerVectorEditor') // do not count those
{
fill = canvas.item(x).get('fill');
if(!(fill in gColorArea)) { gColorArea[fill]=0; }
gColorArea[fill]+=gAll;
gColorList.push(SIGN.fillColors[fill]+'|'+ canvas.item(x).get('text').replace('|',''));
}
break;
case 'image':
case 'group':
if(canvas.item(x).mmkLayerType == 'layerVectorResult') // DO NOT CALC
{
// wenn vectorResult muss der Sibling als Text erwaehnt werden "gAll" bei i-text ercheinen
var sibling = getVectorResultSibling(canvas.item(x),'layerVectorEditor');
if(sibling!=0)
{
fill = canvas.item(sibling).get('fill');
if(!(fill in gColorArea)) { gColorArea[fill]=0; }
gColorArea[fill]+=gAll;
gColorList.push(SIGN.fillColors[fill]+'|'+ canvas.item(sibling).get('text').replace('|',''));
}
}
else
{
fill = canvas.item(x).get('fill');
if(!(fill in gColorArea)) { gColorArea[fill]=0; }
gColorArea[fill]+=gAll;
gColorList.push(SIGN.fillColors[fill]+'|'+'Image');
}
break;
}
}
if(canvas.item(x).get('type')=='image') { bildmontage=1; }
}
LOG && console.log('Gravur:' + gFull +' / Ausschnitte:' + sFull);
// GROUP FILL COLORS
for (var key in gColorArea) { gColorRoam= gColorRoam + key +'|'+ gColorArea[key] +'###'; }
//console.log('Farbliste:');
//console.log(gColorList);
//console.log('gColorArea:');
//console.log(gColorArea);
//console.log('gColorRoam:');
//console.log(gColorRoam);
// INIT LOADER
// $('#wkPrice').html('Lade...
');
// AJAX UPDATE
var dataURL='';
var formData = $('#imUploader').serializeArray(); //$('input[name^="wdata\\["]').serializeArray();
// GET REFPNG // CAUSES SOME REALLY ANNOYING ERRORS + SLOW EITHER
var obj = canvas.getActiveObject();
// CALUCLATE PRICE (PHP)
if(type==1 || type==2)
{
// CREATE SCREENSHOT - HIDE SHADOW
//canvas.item(0).setShadow({ color: 'rgba(0,0,0,0.5) 0 0 0'});
canvas.item(0).set('shadow', new fabric.Shadow('rgba(0,0,0,0.5) 0 0 0'));
var dataRef='';
var objtyp = canvas.item(0).get('type');
/** REMOVE SCALING FROM VIEWPORT **/
var baseTransform = canvas.viewportTransform;
canvas.viewportTransform = fabric.iMatrix.slice(0);
switch(objtyp)
{
case 'rect':
case 'ellipse':
//dataRef = canvas.toDataURL({format: 'png', left: canvas.item(0).get('left'), top: canvas.item(0).get('top'), width: canvas.item(0).get('width'), height: canvas.item(0).get('height')});
dataRef = canvas.toDataURL({format: 'png', left: canvas.item(0).left, top: canvas.item(0).top, width: canvas.item(0).width, height: canvas.item(0).height});
break;
case 'circle':
case 'polygon':
case 'triangle':
case 'path':
case 'path-group':
case 'group' :
//dataRef = canvas.toDataURL({format: 'png', left: canvas.item(0).get('left'), top: canvas.item(0).get('top'), width: canvas.item(0).get('width') * canvas.item(0).get('scaleX'), height: canvas.item(0).get('height') * canvas.item(0).get('scaleY')});
dataRef = canvas.toDataURL({format: 'png', left: canvas.item(0).left, top: canvas.item(0).top, width: canvas.item(0).width * canvas.item(0).scaleX, height: canvas.item(0).height * canvas.item(0).scaleY});
break;
}
// SHOW SHADOW
//canvas.item(0).setShadow({ color: 'rgba(0,0,0,0.5) 0 0 15px' });
canvas.item(0).set('shadow', new fabric.Shadow('rgba(0,0,0,0.5) 0 0 15px'));
var json = JSON.stringify(canvas);
//alert(json);
//json = json.replace(/'/g, "\\'"); //json=replace
//json = json.replace(/'/g, '\'')
//alert(json);
// AJAX UPDATE REQUEST
switch(type)
{
case 2: //onunloadEvent
var oufd = new FormData();
$(formData).each(function(c, item)
{
if(item.name!='JSCONFIG') { oufd.append('OUFD_' + item.name, item.value); }
});
oufd.append('com', 'cs');
oufd.append('json', json);
oufd.append('ref', ''); //dataRef
oufd.append('gf', parseFloat(gFull).toFixed(3));
oufd.append('su', parseFloat(sFull).toFixed(3));
oufd.append('width', canvas.item(0).get('height'));
oufd.append('height', canvas.item(0).get('height'));
oufd.append('gca', gColorRoam);
oufd.append('gcalist', gColorList);
oufd.append('bildmontage', bildmontage);
oufd.append('staerke', staerke);
oufd.append('fixholedata', fixHoleData);
oufd.append('csdatamode', 1);
// seems only 64KB possible
navigator.sendBeacon("https://schilderstyle.de/konfigurator/scripts/mmk-io.php", oufd);
//$.ajax({ url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php",
// type: 'POST',
// cache: false,
// timeout: 30000,
// async: true,
// data: { data: formData, com: 'cs', json: json, ref: dataRef, gf: parseFloat(gFull).toFixed(3), su: parseFloat(sFull).toFixed(3), width: canvas.item(0).get('height'), height: canvas.item(0).get('height'), gca: gColorRoam, gcalist: gColorList, bildmontage: bildmontage, staerke: staerke, fixholedata: fixHoleData },
// error: function(){
// return true;
// },
// success: function(cs) { $('#wkPrice').html(cs); return true; }
//});
break;
default:
$.ajax({ url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php",
type: 'POST',
cache: false,
timeout: 30000,
async: false,
data: { data: formData, com: 'cs', json: json, ref: dataRef, gf: parseFloat(gFull).toFixed(3), su: parseFloat(sFull).toFixed(3), width: canvas.item(0).get('height'), height: canvas.item(0).get('height'), gca: gColorRoam, gcalist: gColorList, bildmontage: bildmontage, staerke: staerke, fixholedata: fixHoleData },
error: function(){
return true;
},
success: function(cs) { $('#wkPrice').html(cs); return true; }
});
}
/** READ SCALING FROM VP **/
canvas.viewportTransform = baseTransform;
}
else
{ $('#wkPrice').html('OFF'); }
// CALUCLATE PRICE (JS)
jsPrice = calculateSignJS(parseFloat(gFull).toFixed(3),parseFloat(sFull).toFixed(3),gColorRoam,bildmontage);
// CALCULATE STUECK NETTO (JS)
jsPriceLC = jsPrice.replace(/\,/,'.');
var TAXSET = parseFloat(19.00);
var TAXCALCMETHOD = '1';
var TAX = parseFloat(100 + TAXSET);
//alert(TAX +', ' + TAXSET +', ' +TAXCALCMETHOD);
//var jsPriceStueck = parseFloat((jsPriceLC/119 * 100) / $('#MENGE').val()).toFixed(2);
if(TAXCALCMETHOD==1)
{
//var jsPriceStueck = parseFloat((jsPriceLC/119 * 100) / $('#MENGE').val()).toFixed(2);
var jsPriceStueck = parseFloat((jsPriceLC/TAX * 100) / $('#MENGE').val()).toFixed(2);
}
else
{
}
jsPriceStueck = jsPriceStueck.replace(/\./,',');
// PRICE OUT
/**
$('#wkPriceJS').html(jsPrice + ' €
inkl. MwSt.');
$('.wkRespPrice').html('Preis: ' + jsPrice + ' € inkl. MwSt.');
$('#wkPriceNetto').html(jsPriceStueck +' € / Stück netto');
**/
$('#wkPriceJS').html(jsPriceStueck +' €
netto / Stück');
$('.wkRespPrice').html('Preis: ' + jsPrice + ' € inkl. MwSt.');
$('#wkPriceNetto').html(jsPrice + ' € inkl. MwSt.');
// SELECT ACTIVE OBJECT
if(obj) { canvas.setActiveObject(obj); }
// REFRESH OBJ LIST / EBENEN
refreshLayerList();
var tdiff = timer(start);
LOG && console.log('Calculated Price in: ' +tdiff);
// ALWAYS MAKE SURE UNSELECTABLE
if(canvas.item(0)!==undefined) { canvas.item(0).selectable=false; }
if(canvas.item(1)!==undefined) { canvas.item(1).selectable=false; }
handleInputs('enable');
}
/** ---------------------------------------------------------------------------*/
/** CALCULATE SIGN (JS ONLY) */
/** ---------------------------------------------------------------------------*/
function calculateSignJS(gf,su,gca,bm)
{
handleInputs('disable');
// GET JSON
var SHIELD = JSON.parse(SCONFIG);
// GET MATERIAL + PRODUCT
var matid = $('#MATERIALID').val();
var prodid = $('#PRODUCTID').val();
var colorid = $('#COLORID').val();
var formid = $('#FORMID').val();
var engraveid = $('#ENGRAVEMETHOD').val();
var MAT = SHIELD[matid];
var PROD = new Object();
var COLOR = new Object();
var SIGN_FORM = new Object();
var ENGRAVE = new Object();
$.each(MAT['PRODUCTS'],function(index, value){
if(value['PID']==prodid) { PROD = MAT['PRODUCTS'][index]; }
});
$.each(PROD['COLORS'],function(index, value)
{
if(value['CID']==colorid) { COLOR = PROD['COLORS'][index]; }
});
$.each(PROD['SIGN_FORMS'],function(index, value)
{
if(value['SFID']==formid) { SIGN_FORM = PROD['SIGN_FORMS'][index]; }
});
$.each(PROD['ENGRAVE_METHODS'],function(index, value) {
if(value['EMID']==engraveid) { ENGRAVE = PROD['ENGRAVE_METHODS'][index]; }
});
/** ----------------------------------------------------------------------*/
var jsPrice='0.00';
// SIGN DIMS
if($("input[name=DIMMODE]:checked").val()==0) { var dim = $('#DIMSTD').val().split("x"); var width=dim[0]; var height=dim[1]; }
else { var width=$('#WIDTH').val(); var height=$('#HEIGHT').val(); }
var width = width/10;
var height = height/10;
var mflaeche = width * height;
var mumfang = width * 2 + height * 2;
// MATERIAL FLAECHE
var mprice = parseFloat(mflaeche) * parseFloat(PROD['PMK_CM2']);
var mpriceDis = mprice.toFixed(2);
// MATERIALZ
var materialzuschlag = mprice * (COLOR['CPA']/100);
// ZUSCHNITT
var mzuschnitt = mumfang * PROD['PZK_CM'];
var mzuschnittDis = mzuschnitt.toFixed(2);
jsPrice = parseFloat(mprice) + parseFloat(mzuschnitt) + parseFloat(materialzuschlag);
// RAB
var groundPrice = jsPrice;
//jsPrice = jsPrice/0.8;
var discountAdd = (jsPrice - groundPrice).toFixed(2);
// MEN RAB
var tp = $('#TIERCONFIG').val().split("|");
var tierPrice50 = tp[0]/100;
var tierPrice100 = tp[1]/100;
var tierPrice500 = tp[2]/100;
var tierPrice1000 = tp[3]/100;
var oldMPrice = jsPrice;
var rabattaufschlag = jsPrice - oldMPrice;
var rabattaufschlagDis = rabattaufschlag.toFixed(2);
var rabatt=0;
if($('#MENGE').val() < 5) { }
else if ($('#MENGE').val() < 10) { jsPrice = jsPrice * (1 - tierPrice50); rabatt=tp[0]; }
else if ($('#MENGE').val() < 50) { jsPrice = jsPrice * (1 - tierPrice100); rabatt=tp[1]; }
else if ($('#MENGE').val() < 100) { jsPrice = jsPrice * (1 - tierPrice500); rabatt=tp[2]; }
else { jsPrice = jsPrice * (1 - tierPrice1000); rabatt=tp[3]; }
var rabattDiff = (rabattaufschlagDis - (jsPrice - oldMPrice)).toFixed(2);
// MINDES
var priceForm = 0;
var priceSondermasz = 0;
// FORM MP
priceForm = SIGN_FORM['MP'];
// SONDER
if($("input[name=DIMMODE]:checked").val()==1)
{
priceSondermasz = PROD['PMP_SM'];
}
// RAB
var discountDis = $('#DISCCONFIG').val();
var discount = $('#DISCCONFIG').val()/100;
var aktionsrabatt = (jsPrice * discount).toFixed(2);
// FORM
var formprice = SIGN_FORM['SFPA'];
jsPrice = parseFloat(jsPrice) + parseFloat(formprice);
var materialprice = parseFloat(jsPrice).toFixed(2);
// GRAVUR
var gravurflaeche = gf; //$SOURCE['GRAVURFLAECHE'];
var gravurpreis = gravurflaeche * ENGRAVE['EMGK_CM2']; //$EM['EMGRAVURKOSTEN_CM2'];
var gravurFlaechenPreis = gravurpreis.toFixed(2);
var gravurAufschlag = (gravurpreis * (ENGRAVE['PEMPAPROZ']/100));
var gravurAufschlagDis = gravurAufschlag.toFixed(2);
var gravurAufschlagQR = 0;
if($('#HAS_QRCODES').val() == 1)
{
var gravurAufschlagQR = (gravurpreis * (ENGRAVE['PEMPA_QR_PROZ']/100));
var gravurAufschlagQRDis = gravurAufschlagQR.toFixed(2);
}
gravurpreis = gravurpreis + gravurAufschlag + gravurAufschlagQR;
// MIN SCHILD
var minPricePerSign = 0;
var chkm = $('#MENGE').val();
var chkmps = new Array();
var chkx = 0;
$.each(ENGRAVE['EM_MINIMUM_QUANTITIES'],function(index, value) {
if(value['EMID']==$('#ENGRAVEMETHOD option:selected').val())
{
chkmps[chkx]=value['MQPPS'];
chkx++;
}
});
if(chkm<5) { minPricePerSign = chkmps[0]; }
else if(chkm<10) { minPricePerSign = chkmps[1]; }
else if(chkm<25) { minPricePerSign = chkmps[2]; }
else if(chkm<50) { minPricePerSign = chkmps[3]; }
else if(chkm<75) { minPricePerSign = chkmps[4]; }
else if(chkm<100) { minPricePerSign = chkmps[5]; }
else if(chkm<250) { minPricePerSign = chkmps[6]; }
else if(chkm<500) { minPricePerSign = chkmps[7]; }
else if(chkm<1000) { minPricePerSign = chkmps[8]; }
else { minPricePerSign = chkmps[9]; }
// GRAVURFLACHE
var gravurMindestPreisAktiv='Ja';
var gravurAktiv='';
if(gravurflaeche!=0)
{
if(gravurpreis 0)
{
var frow= gca.split("###");
xs=1
for(x=0; x ENGRAVE['EMFF_MP_PF'])
{
fbauslage = fcrow;
}
else
{
fbauslage = ENGRAVE['EMFF_MP_PF'];
farbeMinAktiv = 'Nein';
}
farbtmp= '+ Farbe ' + xs +': ' + fc + ' * ' + ENGRAVE['EMFF_MP_PF'] + ' = ' + fcrow + ' > ' + ENGRAVE['EMFF_MP_PF'] + ' (' +farbeMinAktiv +')' + "\n";
farbstr = farbstr + farbtmp;
farbauslage= parseFloat(farbauslage) + parseFloat(fbauslage);
}
xs++;
}
}
var farbauslageDis = parseFloat(farbauslage).toFixed(2);
// SERIENTEXT
var serientextPreis ='0.00'; var serienTextRows='0.00'; var zeilenCount=0; var serienTextRowsMore='Nein'; var words = new Array();
var txtdata=$('#TXTDATA').val();
var xs=0;
if(txtdata.length > 0)
{
rows = txtdata.split("|");
for (x=0; x0)
{
if(first==0) { serienTextRows= parseFloat(serienTextRows) + parseFloat(ENGRAVE['EM_P_ZEILE']); }
else { serienTextRows= parseFloat(serienTextRows) + parseFloat(ENGRAVE['EM_P_NEXTZEILE']); }
zeilenCount++; first=1;
}
}
xs=0;
words= new Array();
}
}
serientextPreis = serienTextRows > ENGRAVE['EM_P_MAXZEILE'] ? ENGRAVE['EM_P_MAXZEILE'] : serienTextRows;
serienTextRowsMore = serienTextRows > ENGRAVE['EM_P_MAXZEILE'] ? 'Ja' : 'Nein';
serientextPreis= parseFloat((serientextPreis/$('#MENGE').val())).toFixed(2);
}
// BEFESTIGUNG
var fxprice=0;
var SIGN_FORMS = new Array(); var FIXATION= new Array();
$.each(PROD['SIGN_FORMS'],function(index, value)
{
if(value['SFID']==$('#FORMID').val()) { SIGN_FORMS = PROD['SIGN_FORMS'][index]; }
});
//if(SIGN_FORMS['SFFIXATIONS']!==null)
if(SIGN_FORMS['SFFIXATIONS'].length > 0)
{
$.each(SIGN_FORMS['SFFIXATIONS'],function(index, value)
{
if(value['FXID']==$('#FIXATIONID').val()) { FIXATION = SIGN_FORMS['SFFIXATIONS'][index]; }
});
if(FIXATION['FXMODE']==0)
{
fxprice=parseFloat(FIXATION['FXP_ST']);
}
else if(FIXATION['FXMODE']==1)
{
fxprice = parseFloat(FIXATION['FXP_CM2'] * (mflaeche/10));
if(fxprice<=FIXATION['FXMP']) { fxprice= parseFloat(FIXATION['FXMP']); }
}
}
// ZUBEHOER / KOMPONENTEN
var componentprice=0;
var componentList = getComponents();
for(var key in componentList)
{
$.each(PROD['COMPONENTS'],function(index, value) {
//console.log('cp: ' + key + ',' + index + ',' + value['CPID']);
if(value['CPID'] == key)
{ componentprice = componentprice + (value['CPPREIS_STUECK'] * componentList[key]); }
});
}
// ADD PROGRAMMKOSTEN + BILDMONTAGE TO ALL (IF FRAESGRAVUR)
var programmkosten = ENGRAVE['EMPK'];
var bildmontage = bm==1 ? ENGRAVE['EMBILDMONTAGE'] : '0.00';
//alert(jsPrice);
jsPrice = parseFloat(jsPrice) + parseFloat(gravurpreis) + parseFloat(ausschnittpreis) + parseFloat(farbauslage) + parseFloat(serientextPreis) + parseFloat(ENGRAVE['EMHANDLING']) + parseFloat(fxprice) + componentprice;
jsPrice = parseFloat(jsPrice).toFixed(2);
var pricePerSign = jsPrice;
var priceAllSigns= (jsPrice * $('#MENGE').val()).toFixed(2);
//alert(priceAllSigns + ', ' + $('#MENGE').val());
var priceFormOrSondermasz = parseFloat(priceForm) > parseFloat(priceSondermasz) ? priceForm : priceSondermasz;
var priceFormDis = parseFloat(priceForm) > parseFloat(priceSondermasz) ? 'Ja' : 'Nein';
var priceSondermaszDis = parseFloat(priceForm) > parseFloat(priceSondermasz) ? 'Nein' : 'Ja';
if(priceFormOrSondermasz==0 || 0.00) { priceFormDis='Nein'; priceSondermaszDis='Nein'; }
jsPrice = jsPrice * parseInt($('#MENGE').val()) + parseFloat(priceFormOrSondermasz) + parseFloat(programmkosten) + parseFloat(bildmontage);
jsPrice = parseFloat(jsPrice * 1.19).toFixed(2);
jsPrice = jsPrice.replace(".",",");
/**
PRLOG && console.log('PriceCALC: ' +width, height);
PRLOG && console.log('-----------------------------------------------------------------------------')
PRLOG && console.log('+ A: ' + mflaeche +' cm2 * '+ PROD['PMK_CM2'] +' = ' + mpriceDis + ' EUR');
PRLOG && console.log('+ U: ' + mumfang + ' cm * '+ PROD['PZK_CM'] + ' = ' + mzuschnittDis + ' EUR');
PRLOG && console.log('+ Materialzuschlag: ' + materialzuschlag + ' EUR (' + COLOR['CPA'] +' %)');
PRLOG && console.log('+ Rabatt auf Mat: ' + discountAdd + ' EUR (20%)');
PRLOG && console.log('+ Mengenstaffelaufschlag: ' + rabattaufschlagDis +' EUR');
PRLOG && console.log('- Gewaehrter Mengenrabatt: ' + rabattDiff + ' EUR (' + rabatt +' %)');
PRLOG && console.log('+ Form: ' + formprice+' EUR ');
PRLOG && console.log('= Materialpeis: ' + materialprice + ' EUR ');
PRLOG && console.log('-----------------------------------------------------------------------------');
PRLOG && console.log('+ Gravur: ' + gravurflaeche +' cm2 * ' + ENGRAVE['EMGK_CM2'] + ' = ' +gravurFlaechenPreis +' EUR ');
PRLOG && console.log('+ Gravuraufschlag: ' + ENGRAVE['PEMPAPROZ'] + ' % = ' + gravurAufschlagDis + ' EUR ');
PRLOG && console.log('> MinGravurPreis/Schild?: ' + minPricePerSign + ' EUR ('+gravurMindestPreisAktiv+')');
PRLOG && console.log('= Gravurpreis: ' + gravurpreisDis + ' EUR ' + gravurAktiv);
PRLOG && console.log('-----------------------------------------------------------------------------');
PRLOG && console.log('+ Ausschnitte: ' + ausschnittumfang + ' cm * ' + PROD['PZK_CM'] + ' = ' +ausschnittpreisDis + ' EUR');
PRLOG && console.log('-----------------------------------------------------------------------------')
PRLOG && console.log(farbstr);
PRLOG && console.log('= Farbe auslegen: ' + farbauslageDis + ' EUR');
PRLOG && console.log('-----------------------------------------------------------------------------');
PRLOG && console.log('+ Befestigung: ' + fxprice + ' EUR ');
PRLOG && console.log('+ Zubehoer: ' + componentprice + ' EUR ');
PRLOG && console.log('+ Handling: ' + ENGRAVE['EMHANDLING'] + ' EUR');
PRLOG && console.log('= Preis pro Schild: ' + pricePerSign + ' EUR ');
PRLOG && console.log('-----------------------------------------------------------------------------');
PRLOG && console.log('+ Serientext: ' + serienTextRows +' EUR ('+ zeilenCount +' Zeilen)');
PRLOG && console.log('> Maximalpreis?: ' + ENGRAVE['EM_P_MAXZEILE'] + ' EUR (' +serienTextRowsMore +')');
PRLOG && console.log('= Serientext (pro Schild): ' + serientextPreis +' EUR ');
PRLOG && console.log('-----------------------------------------------------------------------------');
PRLOG && console.log('+ Preis alle Schilder: ' + priceAllSigns + ' EUR');
PRLOG && console.log('+ MinBest.Wert Schildform?: ' + priceForm + ' EUR (' +priceFormDis+')');
PRLOG && console.log('+ MinBest.Wert Sondermasse?: ' + priceSondermasz + ' EUR (' +priceSondermaszDis+ ')');
PRLOG && console.log('+ Programmkosten: ' + programmkosten + ' EUR (pro Auftrag)');
PRLOG && console.log('+ Bildmontage: ' + bildmontage + ' EUR (pro Auftrag)');
PRLOG && console.log('= Gesamtpreis: ' + jsPrice + ' EUR (Netto)');
PRLOG && console.log('-----------------------------------------------------------------------------');
**/
handleInputs('enable');
return jsPrice;
}
/** ---------------------------------------------------------------------------*/
/** UPDATE OBJECTS FROM CONTROLS */
/** Recalcs Objects size + pos from form elements like ... */
/** ---------------------------------------------------------------------------*/
async function updateObjFromControls(mode)
{
var obj = canvas.getActiveObject();
var type = 'none';
var proportional = true;
var minHeight = parseFloat($('#ENGRAVEMINFONTSIZE').val());
if(obj)
{
type = obj.get('type');
// var proportional INACTIVE FOR NOW, as it would change classic width/height scaling behaviour
if(obj.mmkLayerType == 'layerCutForm' || type=='image' || type=='path')
{ proportional = false; }
LOG && console.log('Type: ' +type+ ', Proportional: ' +proportional);
} else { return; }
// AUTO CORRECT OBJECT / FONT SIZE (HEIGHT)
if(parseFloat($('#objHeight').val()) < minHeight || parseFloat($('#textSize').val()) < minHeight)
{
$('#objHeight').val(parseFloat($('#ENGRAVEMINFONTSIZE').val()));
$('#textSize').val(parseFloat($('#ENGRAVEMINFONTSIZE').val()));
var height = parseFloat($('#objHeight').val()) * SIGN.scaleFac;
var ratio = height / obj.height;
obj.set({'scaleX': ratio, 'scaleY': ratio});
}
// SCALE OBJECT SIZE
if(mode=='scaleX')
{
var width = parseFloat($('#objWidth').val()) * SIGN.scaleFac;
var ratio = width / obj.width;
if(obj.mmkLayerType=='layerCutForm')
{
// unproportional
obj.set('scaleX', ratio);
$('#objWidth').val($('#objWidth').val());
}
else
{
// proportional
obj.set({'scaleX': ratio, 'scaleY': ratio});
$('#objHeight').val(((obj.height * obj.scaleY) / SIGN.scaleFac).toFixed(1));
$('#objWidth').val($('#objWidth').val());
}
//if(type=='i-text') { $('#textSize').val($('#objHeight').val()); }
}
else if(mode=='scaleY')
{
var height = parseFloat($('#objHeight').val()) * SIGN.scaleFac;
var ratio = height / obj.height;
if(obj.mmkLayerType=='layerCutForm')
{
// unproportional
obj.set('scaleY', ratio);
$('#objHeight').val($('#objHeight').val());
}
else
{
// proportional
obj.set({'scaleX': ratio, 'scaleY': ratio});
$('#objWidth').val((obj.width * obj.scaleX / SIGN.scaleFac).toFixed(1));
$('#objHeight').val($('#objHeight').val());
}
//if(type=='i-text') { $('#textSize').val($('#objHeight').val()); }
}
else if(mode=='scaleText')
{
var height = parseFloat($('#textSize').val()) * SIGN.scaleFac;
var ratio = height / obj.height;
obj.set({'scaleX': ratio, 'scaleY': ratio});
$('#objWidth').val((obj.width * obj.scaleX / SIGN.scaleFac).toFixed(1));
$('#objHeight').val($('#textSize').val());
}
else if(mode=='posX')
{
var left = parseFloat(($('#objXPos').val() * SIGN.scaleFac) + canvas.item(0).get('left'));
obj.set('left', left);
$('#objYPos').val(parseFloat((obj.get('top') - canvas.item(0).get('top')) / SIGN.scaleFac).toFixed(1));
}
else if(mode=='posY')
{
var top = parseFloat(($('#objYPos').val() * SIGN.scaleFac) + canvas.item(0).get('top'));
obj.set('top', top);
$('#objXPos').val(parseFloat((obj.get('left') - canvas.item(0).get('left')) / SIGN.scaleFac).toFixed(1));
}
else if (mode=='angle')
{
if($("#objAngle").val().length > 0 && $('#objAngle').val()>= 0 && $('#objAngle').val() <=359) {}
else { $('#objAngle').val('0'); }
obj.set({ angle: parseFloat($('#objAngle').val()) });
}
if(obj.type=='i-text')
{
$('#textSize').val($('#objHeight').val());
await vectorizeFont(obj,'obj_modified',obj.type);
//console.log('nicht synchron');
}
// RESTORE CUTFORM DISPLAYrestore cutform borders
if(obj.mmkLayerType=='layerCutForm' || obj.mmkRenderAsCutForm)
{
restoreCutFormBorder(obj);
}
obj.setCoords();
canvas.renderAll();
setBlackWhiteControlPos();
refreshMiniView(); // ???
LOG && console.log('UpdateObjFromControls: Mode: ' + mode+', Type: ' +type );
}
/** ---------------------------------------------------------------------------*/
/** UPDATE OBJECT CONTROLS */
/** Recalcs Objects size + pos from Canvas/Object */
/** ---------------------------------------------------------------------------*/
async function updateObjControls(source)
{
// if(obj.mmkObjError) // Ein oder Mehrere Objekte
// {
// $('#errorbar').hide();
// }
// FIX DISABLE ALL CLICK EVENTS
handleInputs('disable');
hideBlackWhiteControl();
var obj = canvas.getActiveObject();
var type ='';
var strokeWidth=0;
if(obj) { type = obj.get('type'); }
if(source=='selection:cleared') { hideObjControls(); }
$('#textSelector, #textCutSelector').hide();
$('#objEditFontSelector').hide();
$('#textFontList, .textFontList').hide(); // Maybe still open
$('#textCutFontList, .textCutFontList').hide(); // Maybe still open
//console.log('UpdateObjControls: Type: ' +type+ ', Event: '+source);
switch(type)
{
case 'i-text':
if(obj.mmkRenderAsCutForm)
{
//$('#textCutSelector').is(':hidden') ? $('#textCutSelector').show(): '';
$('#textSelector').hide();
$('.textFontSelector').hide();
$('#textCutSelector').show();
$('.textCutFontSelector').show();
}
else
{
//$('#textSelector').is(':hidden') ? $('#textSelector').show(): '';
$('#textCutSelector').hide();
$('.textCutFontSelector').hide();
$('#textSelector').show()
$('.textFontSelector').show();
}
$('#objEditFontSelector').is(':hidden') ? $('#objEditFontSelector').show() : '';
// RESTORE SST_NAME TO ORIGINAL FONT NAME
var vectorFont = getVectorFontFamilyName(obj);
if(vectorFont.length > 0)
{
if(obj.mmkRenderAsCutForm)
{
//console.log('Setting Vector Font: ' + vectorFont)
$('#textCutFontSelector').val(vectorFont); // i.e. Montserrat
$('.textCutFontSelector').val(vectorFont);
}
else
{
$('#textFontSelector').val(vectorFont); // i.e. Montserrat
$('.textFontSelector').val(vectorFont);
}
}
else
{
if (!$('#textFontSelector option[value="' +obj.fontFamily+ '"]').prop("selected", true).length) {
//$('#textFontSelector').val($("#textFontSelector option:first").val());
chooseText($("#textFontSelector option:first").val());
}
else
{
//console.log('ELSE EDGE CASE'); // defaults to non vector
$('#textFontSelector').val(obj.fontFamily);
$('.textFontSelector').val(obj.fontFamily);
}
}
// RENDER SVG IF MODIFIED OR OBJ_MODIFIED OR ON CREATION
await vectorizeFont(obj,source,type); // i.e. Montserrat
// TEXT SIZE
//var textSize = parseFloat(obj.get('height') * obj.get('scaleY')/SIGN.scaleFac).toFixed(1);
var textSize = parseFloat(obj.height * obj.scaleY / SIGN.scaleFac).toFixed(1);
if(textSize < parseFloat($('#ENGRAVEMINFONTSIZE').val())) { textSize=$('#ENGRAVEMINFONTSIZE').val(); /** $('#errorbar').html('Ups, Die Mindestschrifth\u00F6he f\u00FCr diese Gravurmethode liegt bei ' +$('#ENGRAVEMINFONTSIZE').val()+'mm!'); $('#errorbar').show(); **/ }
$('#textSize').val(textSize);
// GET TEXT PROPERTIES
$('.textBold').each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); if(obj.fontWeight=='bold') { $('.textBold').addClass('gradSelect'); }
$('.textItalic').each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); if(obj.fontStyle =='italic') { $('.textItalic').addClass('gradSelect'); }
$('.textUnderline').each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); if(obj.underline==true) { $('.textUnderline').addClass('gradSelect'); }
// GET TEXT ALIGNMENT
var align= obj.get('textAlign');
switch(align)
{
case 'left' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textLeft').addClass('gradSelect'); break;
case 'center' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textCenter').addClass('gradSelect'); break;
case 'right' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textRight').addClass('gradSelect'); break;
}
// SET TEXT INPUT FIELD
if(obj.mmkSerienText)
{
$('#textBox').val('Es ist ein Serientextfeld ausgewählt. Um den Text zu bearbeiten klicken Sie bitte oben auf "Serientext / Importieren');
$('#textBox').prop('disabled', true);
}
else
{
if(obj.mmkRenderAsCutForm)
{
$('#textCutBox').val(obj.text);
$('#textCutBox').prop('disabled', false);
}
else
{
$('#textBox').val(obj.text);
$('#textBox').prop('disabled', false);
}
}
fabric.util.clearFabricFontCache();
break;
case 'image':
if(obj.filters[0])
{
showBlackWhiteControl(obj, obj.filters[0]['distance']);
}
break;
case 'path-group': break; // doesn't exist anymore
case 'group':
if(obj.mmkLayerType=='layerVectorResult')
{
var sibling = getVectorResultSibling(obj,'layerVectorEditor');
if(sibling!=0) { canvas.item(sibling).set({'left': obj.left, 'top': obj.top, 'scaleX': obj.scaleX, 'scaleY': obj.scaleY}); }
// SHOW FONT SELECTOR
if(obj.mmkRenderAsCutForm)
{
//$('#textCutSelector').is(':hidden') ? $('#textCutSelector').show(): '';
$('#textSelector').hide();
$('.textFontSelector').hide();
$('#textCutSelector').show();
$('.textCutFontSelector').show();
}
else
{
//$('#textSelector').is(':hidden') ? $('#textSelector').show(): '';
$('#textCutSelector').hide();
$('.textCutFontSelector').hide();
$('#textSelector').show();
$('.textFontSelector').show();
}
$('#objEditFontSelector').is(':hidden') ? $('#objEditFontSelector').show() : '';
// SET CORRECT PROPERTIES TO SELECTORS
var vectorFont = getVectorFontFamilyName(canvas.item(sibling));
$('#textFontSelector').val(vectorFont);
$('.textFontSelector').val(vectorFont);
$('.textBold').each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); if(canvas.item(sibling).fontWeight=='bold') { $('.textBold').addClass('gradSelect'); }
$('.textItalic').each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); if(canvas.item(sibling).fontStyle =='italic') { $('.textItalic').addClass('gradSelect'); }
switch(canvas.item(sibling).textAlign)
{
case 'left' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textLeft').addClass('gradSelect'); break;
case 'center' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textCenter').addClass('gradSelect'); break;
case 'right' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textRight').addClass('gradSelect'); break;
}
// SET TEXTBOX VALUE BY LAYER VECTOR GROUP
if(obj.mmkRendersAsCutForm)
{
//checkObjectMiniumHeight(obj);
$('#textCutSize').val($('#objHeight').val());
$('#textCutBox').val(canvas.item(sibling).text);
}
else if(obj.mmkSerienText)
{
$('#textBox').val('Es ist ein Serientextfeld ausgewählt. Um den Text zu bearbeiten klicken Sie bitte oben auf "Serientext / Importieren');
$('#textBox').prop('disabled', true);
}
else
{
$('#textSize').val($('#objHeight').val());
$('#textBox').val(canvas.item(sibling).text);
$('#textBox').prop('disabled', false);
}
}
break;
default:
}
if(obj)
{
checkObjectWidthHeight($('#objWidth').val(),$('#objHeight').val());
// DISPLAY POSITION
$('#objXPos').val(parseFloat((obj.get('left') / SIGN.scaleFac) - (canvas.item(0).get('left') / SIGN.scaleFac)).toFixed(1));
$('#objYPos').val(parseFloat((obj.get('top') / SIGN.scaleFac) - (canvas.item(0).get('top') / SIGN.scaleFac)).toFixed(1));
$('#objWidth').val(parseFloat(obj.get('width') * obj.get('scaleX') / SIGN.scaleFac).toFixed(1));
$('#objHeight').val(parseFloat(obj.get('height') * obj.get('scaleY') / SIGN.scaleFac).toFixed(1));
$('#objAngle').val(parseInt(obj.get('angle')));
//console.log(obj.get('left') +', ' + obj.get('top'));
// SHOW OBJECTEDIT PANEL
if($(window).width()>1024)
{ $('#objectEdit').show(); }
else
{
$('#respObjectEditButton').show();
}
// IF OBJECT TYPE GROUP AND layerCOMPONENT NO SCALE
if(obj.mmkLayerType=='layerComponent')
{
$('#objWidth').prop('readonly', true); $('#objWidth').addClass('inputInactive');
$('#objHeight').prop('readonly', true); $('#objHeight').addClass('inputInactive');
}
else
{
$('#objWidth').prop('readonly', false); $('#objWidth').removeClass('inputInactive');
$('#objHeight').prop('readonly', false); $('#objHeight').removeClass('inputInactive');
}
// RESTORE CUTFORM DISPLAYrestore cutform borders
if(obj.mmkLayerType=='layerCutForm' || obj.mmkRenderAsCutForm)
{
restoreCutFormBorder(obj);
}
// RESTORE IF ACTIVE layerVectorResult
var activeObj = canvas.getActiveObject(); // could be != obj
if(activeObj.mmkLayerType == 'layerVectorResult')
{
$('#objWidth').val(parseFloat(activeObj.width * activeObj.scaleX / SIGN.scaleFac).toFixed(1));
$('#objHeight').val(parseFloat(activeObj.height * activeObj.scaleY / SIGN.scaleFac).toFixed(1));
if(obj.mmkRenderAsCutForm)
{
$('#textCutSize').val($('#objHeight').val());
}
else
{
$('#textSize').val($('#objHeight').val());
}
}
}
// RENDER
//canvas.renderAll();
// REFRESH MINi VIEW FOR BETTER PERFORMANCE
delay(function() { refreshMiniView(); }, SIGN.miniViewRefreshDelay);
// CALCULATE SIGN
calculateSign('updateObjControls',0);
handleInputs('enable');
}
// FOR SHOWING/HIDING CONTROLS
function hideObjControls()
{
$('#textSelector').hide();
$('#textCutSelector').hide();
// SHOW OBJECTEDIT PANEL
//if($('#objXPos').is(':focus'))
//{} else {
$('#objectEdit').hide();
//}
if(isResponsiveViewport() === true)
{
$('#respObjectEditButton').hide();
responsiveMenuElements('show');
}
var obj = canvas.getActiveObject();
if(obj && obj.mmkLayerType=='layerVectorEditor')
{
var sibling = getVectorResultSibling(obj,'layerVectorResult');
if(sibling!=0)
{
obj.set({'opacity': SIGN.fontVectorizeOpacity, 'evented': false, 'selectable': false});
canvas.item(sibling).set({'opacity': 1, 'evented': true, 'selectable': true});
canvas.setActiveObject(canvas.item(sibling));
}
}
}
function refreshLayerList()
{
var objLayerContent=''; $('#objLayers').html();
var schildObjList = [];
var schildNoObjects = "Derzeit befinden sich keine Objekte auf Ihrem Schild
";
//var activeObj = canvas.getActiveObject()
var layerID = 1;
var fakeCount = 1;
var sel = ' grad'
var qrCodesCount = 0;
for(x=1; x1) { selectable=''; selectableEnd=''; }
objLayerContent= objLayerContent + selectable +'Ebene ' + x + ' / '+ objType +'
Typ: '+ layerType +', Fill: '+ layerFill +'
layerUniqueID: '+ layerUniqueID +'
' + selectableEnd;
/** schildObjList */
if(x>1)
{
if(canvas.item(x).mmkLayerType)
{
switch(canvas.item(x).mmkLayerType)
{
case 'layerFixation': break;
case 'layerCutForm':
layerType = 'Ausschnitt';
layerImgClass = ' layerImgCutform';
break;
case 'layerVectorResult':
if(canvas.item(x).mmkRenderAsCutForm)
{
layerType = 'Ausschnitt';
layerImgClass = ' layerImgCutform';
}
else if(canvas.item(x).mmkSerienText)
{
layerType = 'Serientext';
layerImgClass = ' layerImgText';
}
else
{
layerType = 'Text';
layerImgClass = ' layerImgText';
}
break;
case 'layerComponent':
layerType = 'Zubehör';
layerImgClass = ' layerImgComponent';
break;
case 'layerBarcode':
layerType = 'Codes';
layerImgClass = ' layerImgCodes';
qrCodesCount++;
break;
}
if(layerType.length > 0 && layerImgClass.length > 0)
{
schildObjList.push(""+fakeCount+" - " + layerType + "
");
fakeCount++;
}
}
else
{
switch(canvas.item(x).type)
{
case 'image':
layerType = 'Bild';
layerImgClass = ' layerImgImage';
break;
case 'i-text':
layerType = 'Text';
layerImgClass = ' layerImgText';
break;
case 'path':
case 'path-group':
case 'group':
layerType = 'Bild';
layerImgClass = ' layerImgImage';
break;
default:
layerType = 'Unbekannt';
layerImgClass = ' layerImgUnknown';
}
if(layerType.length > 0 && layerImgClass.length > 0)
{
schildObjList.push(""+fakeCount+" - " + layerType + "
");
fakeCount++;
}
}
}
layerID++;
}
var objListReverse = schildObjList.slice().reverse();
$('#objLayers').html(objLayerContent);
layerID==2 ? $('.schildObjList').html(schildNoObjects) : $('.schildObjList').html(objListReverse);
// IF NO OBJECTS
if(layerID==2) { $('#serientext').hide(); }
// SET QRCODES
qrCodesCount > 0 ? $('#HAS_QRCODES').val(1) : $('#HAS_QRCODES').val(0);
}
function selectObjListLayer(id,mode)
{
canvas.setActiveObject(canvas.item(id));
if(mode=='dblclick')
{
if(canvas.item(id).mmkLayerType == 'layerBarcode')
{
restoreBarcode();
}
else if(canvas.item(id).mmkSerienText)
{
serienDruckWin.open();
}
}
//console.log('SchildObjLayer:' + canvas.item(id));
}
function selectObjListLayerWithData(id)
{
/* SHOWS FULL OBJECT FOR CONSOLE Click*/
obj = canvas.setActiveObject(canvas.item(id));
console.log(canvas.item(id));
}
function formatObjControls(obj,mode)
{
if(mode==1)
{
var type = obj.get('type');
if(type=='i-text' || obj.mmkLayerType=='layerVectorResult' || obj.mmkLayerType=='layerBarcode')
{
obj['setControlVisible']('ml',0);
obj['setControlVisible']('mb',0);
obj['setControlVisible']('mr',0);
obj['setControlVisible']('mt',0);
}
else { } // show all
/** ROTATE LOCK ? **/
SIGN.lockRotate == 1 ? obj['setControlVisible']('mtr',0) : obj['setControlVisible']('mtr',1);
}
obj['padding']= SIGN.selectorPadding; //4;
obj['cornerSize']=SIGN.selectorCornerSize; //8
obj['borderColor']=SIGN.selectorBorderColor;
obj['cornerColor']=SIGN.selectorCornerColor;
obj['cornerStyle']=SIGN.selectorCornerStyle;
obj['transparentCorners'] = SIGN.selectorCornerTransparent;
//if(obj['mmkLayerType']=='layerSerienText')
// {
// // RE-REGISTER
// obj.set({ caching: false, editable: false, 'borderColor':SIGN.selectorSerienText,'cornerColor':SIGN.selectorSerienText, mmkLayerType: 'layerSerienText' });
// register_mmkLayerType(obj);
//}
// RE-REGISTER OWN VARS // OR THEY WILL DISAPEAR
if(typeof obj['mmkObjectID'] !== 'undefined') { obj.set({ mmkObjectID: obj['mmkObjectID'] }); register_mmkObjectID(obj); }
if(obj['mmkLayerType']=='layerCutForm') { obj.set({ mmkLayerType: 'layerCutForm' }); register_mmkLayerType(obj); }
if(obj['mmkLayerType']=='layerFixation') { obj.set({ selectable: false, mmkLayerType: 'layerFixation' }); register_mmkLayerType(obj); }
if(obj['mmkLayerType']=='layerOverlay') { obj.set({ selectable: false, mmkLayerType: 'layerOverlay' }); register_mmkLayerType(obj); }
if(obj['mmkLayerType']=='layerCompFixation') { obj.set({ selectable: false, mmkLayerType: 'layerCompFixation' }); register_mmkLayerType(obj); }
if(obj['mmkLayerType']=='layerComponent') { obj.set({ selectable: true, mmkLayerType: 'layerComponent', 'borderColor': SIGN.selectorBorderColor,'cornerColor':SIGN.selectorCornerColor });
obj.setControlsVisibility({ mt: false, mb: false, ml: false, mr: false, mtr: false });
register_mmkLayerType(obj); }
if(obj['mmkLayerType']=='layerVectorResult') { extendObject(obj, 'mmkLayerType','layerVectorResult'); }
if(obj['mmkLayerType']=='layerVectorEditor') { extendObject(obj, 'mmkLayerType','layerVectorEditor'); }
if(obj['mmkLayerUniqueID']) { extendObject(obj, 'mmkLayerUniqueID', obj['mmkLayerUniqueID']); }
if(obj['mmkRenderAsCutForm']) { extendObject(obj, 'mmkRenderAsCutForm', true); }
if(obj['mmkSerienText']) { obj.set({'caching': false, 'editable': false, 'borderColor': SIGN.selectorSerienText, 'cornerColor': SIGN.selectorSerienText });
extendObject(obj, 'mmkSerienText', true);
}
if((obj['mmkLayerFill']) && $('#ENGRAVEFILLABLE').val()==1) //=='layerFillColor'
{ obj.set({ mmkLayerFill: 1 }); register_mmkLayerFill(obj); }
// UNREGISTER VARS
if((obj['mmkLayerFill']) && $('#ENGRAVEFILLABLE').val()==0) //=='layerFillColor'
{ obj.set({ mmkLayerFill: '' }); register_mmkLayerFill(obj); }
// TRUE COLOR
if((obj['mmkTrueColor'])==1) { obj.set({ mmkTrueColor: 1 }); register_mmkTrueColor(obj); }
if((obj['mmkImageResolution'])) { obj.set({ mmkImageResolution: obj['mmkImageResolution'] }); register_mmkTrueColor(obj); }
LOG && console.log('FormatObjControls: Obj: '+obj+ ', Mode: ' +mode);
}
/** REGISTERS / EXTENDS NEW PARAMS TO OBJECT (ONLY WAY TO STORE DATA IN JSON) **/
function extendObject(obj, param, val)
{
obj.set({[param]: val});
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
[param]: val
});
};
})(obj.toObject);
}
function register_mmkObjectID(obj)
{
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
mmkObjectID: this.mmkObjectID
});
};
})(obj.toObject);
}
function register_mmkLayerType(obj)
{
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
mmkLayerType: this.mmkLayerType
});
};
})(obj.toObject);
}
function register_mmkLayerFill(obj)
{
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
mmkLayerFill: this.mmkLayerFill
});
};
})(obj.toObject);
}
function register_mmkTrueColor(obj)
{
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
mmkTrueColor: this.mmkTrueColor
});
};
})(obj.toObject);
}
function register_mmkImageResolution(obj)
{
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
mmkImageResolution: this.mmkImageResolution
});
};
})(obj.toObject);
}
/* RESTORES TOP/LEFT X/Y FORM FIELDS ON INVALID INPUT **/
function setCalculateObjXY(obj)
{
if(obj)
{
$('#objXPos').val(parseFloat((obj.get('left') - canvas.item(0).get('left')) / SIGN.scaleFac).toFixed(1));
$('#objYPos').val(parseFloat((obj.get('top') - canvas.item(0).get('top')) / SIGN.scaleFac).toFixed(1));
}
}
/* RESTORES WIDTH/HEIGHT FORM FIELDS ON INVALID INPUT **/
function restoreObjWidthHeight(obj)
{
if(obj)
{
$('#objWidth').val(parseFloat(obj.get('width') * obj.get('scaleX') / SIGN.scaleFac).toFixed(1));
$('#objHeight').val(parseFloat(obj.get('height') * obj.get('scaleY') / SIGN.scaleFac).toFixed(1));
if(obj.type=='i-text') { $('#textSize').val($('#objHeight').val()); }
}
}
function showSignPreview()
{
var br = canvas.item(0).getBoundingRect();
var data = canvas.toDataURL({format: 'png',
left: br['left'],
top: br['top'],
width: br['width'],
height: br['height'],
multiplier: 2,
});
$('.signPreviewContainer').css({'background-image': 'url('+data+')'});
previewWin.open();
}
function setCanvasZoom(mode)
{
handleInputs('disable');
var zoom = canvas.getZoom();
switch(mode)
{
case 'inc': if(!(zoom >= 1.9)) { zoom+=0.1; } else { zoom=2; } break;
case 'dec': if(!(zoom <= 0.2)) { zoom-=0.1; } else { zoom=0.1; }break;
}
canvas.zoomToPoint(new fabric.Point(canvas.width/2, canvas.height / 2), zoom);
showZoomDim('setCanvasZoom');
setBlackWhiteControlPos();
handleInputs('enable');
}
function setCanvasZoomInit(frompoint)
{
handleInputs('disable');
//canvas.setZoom(1);
canvas.setHeight($('#canvasBox').height());
canvas.setWidth($('#canvasBox').width());
canvas.calcOffset();
var canvasWidth = $('#canvasBox').width();
var canvasHeight = $('#canvasBox').height();
var signWidth = (canvas.item(0).width * canvas.item(0).scaleX) + 40 ; // + extra space
var signHeight = (canvas.item(0).height * canvas.item(0).scaleY) + 40; // + extra space
var zoomRatio = canvas.getZoom();
//console.log('setCanvasZoom from ' +frompoint + ' WIDTH/HEIGHT: ' + canvasWidth + ', ' +canvasHeight+ ', ZoomRatio: ' + zoomRatio);
var zoomRatio = canvas.getZoom();
/** AUTO CORRECT */
if(canvasWidth <= signWidth && canvasHeight <= signHeight)
{
//console.log ('WIDTH & HEIGHT < MODE');
zoomRatio = canvasWidth/signWidth < canvasHeight/signHeight ? canvasWidth/signWidth : canvasHeight/signHeight;
//console.log('CANVAS WIDTH + HEIGHT KLEINER > Z: ' + zoomRatio + ' X: ' + ratioX + ' Y: ' + ratioY);
}
else if(canvasWidth < signWidth)
{
//console.log ('MAXHEIGHT MODE');
zoomRatio = canvasWidth/signWidth;
//console.log('CANVAS HEIGHT < SIGN HEIGHT > Z: ' + zoomRatio + ' X: ' + ratioX + ' Y: ' + ratioY);
}
else if(canvasHeight < signHeight)
{
//console.log ('MAXHEIGHT MODE');
zoomRatio = canvasHeight/signHeight;
//console.log('CANVAS HEIGHT < SIGN HEIGHT > Z: ' + zoomRatio + ' X: ' + ratioX + ' Y: ' + ratioY);
}
else
{
zoomRatio = 1;
//canvas.viewportTransform = [1, 0, 0, 1, 0, 0];
canvas.viewportTransform = fabric.iMatrix.slice(0);
// RECALC INITAL SIZE (CANVAS larger than SIGN)
if(signWidth > signHeight)
{
if(canvasWidth > 1024) { zoomRatio = (canvasWidth - 560) / signWidth; } // 560 + sicherheitsabstand Menu
else { zoomRatio = (canvasWidth - 20) / signWidth; }
if((signHeight * zoomRatio) > canvasHeight)
{
//corrrect higher sign than screen
zoomRatio = (canvasHeight - 20) / signHeight;
}
}
else
{
if(signHeight > canvasHeight)
{
zoomRatio = (canvasHeight - 20) / signHeight;
}
else
{
zoomRatio = (canvasHeight - 20) / signHeight;
}
}
}
//console.log('zoomRatio after check: ' + zoomRatio + ', CurrentWidth / Height: ' + signWidth + ', ' + signHeight);
//var zoomLevel = maxWidth > maxHeight ? currentHeight/maxHeight : currentWidthh/maxWidth;
if(zoomRatio <=0.1) { zoomRatio =0.1; }
/** PAN ACTION **/
var w = canvas.width;
var h = canvas.height;
//console.log('PanAction W/H: ' +w+ ', '+h);
var targetX = (canvas.item(0).left + (canvas.item(0).width * canvas.item(0).scaleX) / 2 ) * zoomRatio;
var targetY = (canvas.item(0).top + (canvas.item(0).height * canvas.item(0).scaleY) / 2 ) * zoomRatio
//console.log('Targets: ' +targetX+ ','+targetY+ ' Left/Top: ' + canvas.item(0).left + ', ' + canvas.item(0).top);
canvas.setZoom(zoomRatio);
canvas.absolutePan(new fabric.Point(-w/2+targetX, -h/2+targetY));
for(x=0; x CW/CH: ' + canvas.width +' ,' + canvas.height + '
';
var paninfo = 'ZX/ZY: ' +p['x']+', '+p['y'] +'
VT: ' +vt[0]+','+vt[1]+','+vt[2]+',
'+vt[3]+','+vt[4]+','+vt[5] + '
TP: ' +tp['x'].toFixed(1)+','+tp['y'].toFixed(1);
$('.zoominfo').html(zoominfo);
$('.paninfo').html(paninfo);
//console.log(zoominfo);
//console.log(paninfo);
}
/** MINIVIEW **/
function calcMiniView()
{
LOG && console.log('Calculating Rendered MiniView after loaded JSON');
//var zoomLevel = calcViewPort(miniView,canvas.item(0).width,canvas.item(0).height,100,0);
var zoomLevel = calcViewPort(miniView,canvas.item(0),100,0);
var zoomedx = canvas.item(0).width * canvas.item(0).scaleX * (zoomLevel/100);
var zoomedy = canvas.item(0).height * canvas.item(0).scaleY * (zoomLevel/100);
// console.log('miniViewType: ' +canvas.item(0).type + ', ZoomLevel:' + zoomedx +','+zoomedy+ ', ScaleX :' + canvas.item(0).scaleX + ', ' + canvas.item(0).scaleY) ;
var xdiff = (SIGN.miniViewWidth - zoomedx) / 2;
var ydiff = (SIGN.miniViewHeight - zoomedy) / 2;
//console.log('xdiff (+16): '+xdiff+',ydiff (+11): '+ydiff+',zoomedx: '+zoomedx+',zoomedy: '+zoomedy+',canvasZoom: '+canvas.getZoom()+',miniViewZoom: '+miniView.getZoom());
miniView.viewportTransform = [(zoomLevel/100), 0, 0, (zoomLevel/100), xdiff, ydiff];
//$('#shownarea').css({'width': parseInt(zoomedx+1), 'height': parseInt(zoomedy+1), 'left': parseInt(xdiff+5), 'top': parseInt(ydiff+5) });
miniView.renderAll.bind(miniView);
}
function refreshMiniView()
{
LOG && console.log('Refreshing MiniView');
/** GLOBAL ERROR HANDLER */
var error = 0;
var warn = 0;
$('#errorbar').html('');
$('#warnbar').html('');
/** CHECK ERRORS */
SIGN.error['intersectObj'] = 0;
SIGN.error['fontMinSize'] = 0;
SIGN.warn['imageResLow'] = 0;
var errorMinCutText = 0;
var errorBarCode = 0;
for(xobj=2; xobj0) { $('#errorbar').append('Mehrere Objekte liegen übereinander!
'); }
if(SIGN.error['fontMinSize']>0) { $('#errorbar').append('Die Mindestschrifthöhe für diese Gravurmethode liegt bei ' +$('#ENGRAVEMINFONTSIZE').val()+'mm!
'); }
if(errorMinCutText == 1)
{
if($('#errorbarFix').is(':hidden')) {
$('#errorbarFix').html('Die Mindesthöhe für einen oder mehrere Text-Ausschnitt(e) wurde unterschritten und automatisch angepasst.');
$('#errorbarFix').show().delay(SIGN.errorDelay).fadeOut('slow');
}
}
if(errorBarCode == 1)
{
if($('#errorbarFix').is(':hidden')) {
$('#errorbarFix').html('Die Mindesthöhe für einen oder mehrere QR-Code/Barcodes wurde unterschritten und automatisch angepasst.');
$('#errorbarFix').show().delay(SIGN.errorDelay).fadeOut('slow');
}
}
if(SIGN.warn['imageResLow']>0) { if(SIGN.warn['imageResLow']==1) { $('#warnbar').append('Ein Bild hat eine geringe Auflösung. Das kann zu Qualitätseinbußen führen.'); } else { $('#warnbar').append('Mehrere Bilder haben eine geringe Auflösung. Das kann zu Qualitätseinbußen führen.'); }}
$.each(SIGN.error, function(key,errval) { error+= errval; });
$.each(SIGN.warn, function(key,warnval) { warn+= warnval});
if(error>=1) { $('#errorbar').show(); } else { $('#errorbar').hide(); }
if(warn >=1) { $('#warnbar').show(); } else { $('#warnbar').hide(); }
canvas.renderAll();
var canvasJSON = JSON.stringify(canvas);
//console.log(canvasJSON);
/* REMOVE CLIPPATH */
var objects_obj = JSON.parse(canvasJSON);//object
var objects_array = objects_obj['objects'];
var obj_with_clipPath = objects_array.filter(function(val) { /* 0nly objs having clipPath */
if (val.clipPath !== void 0) return true;
});
var without_clipPath = $.each(objects_array, function(index,elem){
delete elem.clipPath;
})
objects_obj['objects'] = without_clipPath;
var string_objects_data_without_clipPath = JSON.stringify(objects_obj);//JSON
/* LOAD JSON ASYNC -> CALLBACK calcMiniView() */
miniView.loadFromJSON(string_objects_data_without_clipPath, function() { calcMiniView(); miniView.renderAll(); },
function (o, object)
{
//console.log(o);
//console.log(object);
object.set({'left': object.left - canvas.item(0).left,'top': object.top - canvas.item(0).top });
object.setCoords();
});
// miniView.viewportTransform = [1, 0, 0, 1, 0, 0];
// miniView.viewportTransform = fabric.iMatrix.slice(0);
miniView.calcOffset();
miniView.renderAll();
}
function calcViewPort(sourceCanvas,destinationCanvas,maxZoom,zoomCanvas)
{
var zoom = 0;
var zoomLevel = 100;
var displayWidth = sourceCanvas.width / 100 * maxZoom; // 80%
var displayHeight = sourceCanvas.height / 100 * maxZoom;
var x = destinationCanvas.width * destinationCanvas.scaleX;
var y = destinationCanvas.height * destinationCanvas.scaleY;
// console.log(x, y);
if(x>displayWidth || y > displayHeight)
{
zoom=1;
}
LOG && console.log('CalcViewPort => X: ' +x+ ' dpwidth('+displayWidth+'), Y: '+y+' dpheight('+displayHeight+'), SCWidth: '+sourceCanvas.width+', SCHeight: '+sourceCanvas.height);
if(x!=0 && y!=0 && zoom==1)
{
if(x>=y)
{
// xsize calc
if(x>=sourceCanvas.width)
{
//zoomLevel = parseInt(displayWidth/x * 100);
zoomLevel = displayWidth/x * 100;
if(zoomCanvas==1) { setCanvasZoom(sourceCanvas,zoomLevel); }
//alert('CASE 1, ZoomLevel: ' + zoomLevel);
}
if((y/100*zoomLevel) >= sourceCanvas.height) // COULD BE LARGER BECAUSE OF ASPECT RATIO (Square)
{
//alert('y größer als 80% in X-MODE');
//zoomLevel = parseInt(displayHeight/y * 100);
zoomLevel = displayHeight/y * 100;
if(zoomCanvas==1) { setCanvasZoom(sourceCanvas,zoomLevel); }
//alert('CASE 2, ZoomLevel: ' + zoomLevel);
}
}
else
{
// ysize calc
if(y>=sourceCanvas.height)
{
//zoomLevel = parseInt(displayHeight/y * 100);
zoomLevel = displayHeight/y * 100;
if(zoomCanvas==1) { setCanvasZoom(sourceCanvas,zoomLevel); }
// alert('CASE 3');
}
if((x/100*zoomLevel) >= (sourceCanvas.width/100 * maxZoom))
{
//zoomLevel = parseInt(displayWidth/x * 100);
zoomLevel = displayWidth/x * 100;
if(zoomCanvas==1) { setCanvasZoom(sourceCanvas,zoomLevel); }
//alert('CASE 4');
}
}
}
return zoomLevel;
}
/** GUIDELINES **/
function initCenteringGuidelines(canvas) {
var canvasWidth = canvas.getWidth(),
canvasHeight = canvas.getHeight(),
canvasWidthCenter = canvasWidth / 2,
canvasHeightCenter = canvasHeight / 2,
canvasWidthCenterMap = { },
canvasHeightCenterMap = { },
centerLineMargin = 8, //4,
centerLineColor = 'rgba(255,0,241,1)',
centerLineWidth = 1.5,
ctx = canvas.getSelectionContext(),
viewportTransform;
for (var i = canvasWidthCenter - centerLineMargin, len = canvasWidthCenter + centerLineMargin; i <= len; i++) {
canvasWidthCenterMap[Math.round(i)] = true;
}
for (var i = canvasHeightCenter - centerLineMargin, len = canvasHeightCenter + centerLineMargin; i <= len; i++) {
canvasHeightCenterMap[Math.round(i)] = true;
}
function showVerticalCenterLine() {
showCenterLine(canvasWidthCenter + 0.5, 0, canvasWidthCenter + 0.5, canvasHeight);
}
function showHorizontalCenterLine() {
showCenterLine(0, canvasHeightCenter + 0.5, canvasWidth, canvasHeightCenter + 0.5);
}
function showCenterLine(x1, y1, x2, y2) {
var originXY = fabric.util.transformPoint(new fabric.Point(x1, y1), canvas.viewportTransform),
dimmensions = fabric.util.transformPoint(new fabric.Point(x2, y2),canvas.viewportTransform);
ctx.save()
ctx.strokeStyle = centerLineColor
ctx.lineWidth = centerLineWidth
ctx.beginPath()
ctx.moveTo(
( (originXY.x ) ),
( (originXY.y ) )
)
ctx.lineTo(
( (dimmensions.x ) ),
( (dimmensions.y ) )
)
ctx.stroke()
ctx.restore()
}
// function showCenterLine(x1, y1, x2, y2) {
// ctx.save();
// ctx.strokeStyle = centerLineColor;
// ctx.lineWidth = centerLineWidth;
// ctx.beginPath();
// ctx.moveTo(x1 * viewportTransform[0], y1 * viewportTransform[3]);
// ctx.lineTo(x2 * viewportTransform[0], y2 * viewportTransform[3]);
// ctx.stroke();
// ctx.restore();
// }
var afterRenderActions = [],
isInVerticalCenter,
isInHorizontalCenter;
canvas.on('mouse:down', function () {
viewportTransform = canvas.viewportTransform;
});
canvas.on('object:moving', function(e) {
var object = e.target,
objectCenter = object.getCenterPoint(),
transform = canvas._currentTransform;
if (!transform) return;
isInVerticalCenter = Math.round(objectCenter.x) in canvasWidthCenterMap,
isInHorizontalCenter = Math.round(objectCenter.y) in canvasHeightCenterMap;
if (isInHorizontalCenter || isInVerticalCenter) {
object.setPositionByOrigin(new fabric.Point((isInVerticalCenter ? canvasWidthCenter : objectCenter.x), (isInHorizontalCenter ? canvasHeightCenter : objectCenter.y)), 'center', 'center');
}
});
canvas.on('before:render', function() {
//canvas.clearContext(canvas.contextTop);
//canvas.clearContext(ctx);
const ct = canvas.contextTop;
if(ct) { canvas.clearContext(ct); }
});
canvas.on('after:render', function() {
if (isInVerticalCenter) {
showVerticalCenterLine();
}
if (isInHorizontalCenter) {
showHorizontalCenterLine();
}
});
canvas.on('mouse:up', function() {
// clear these values, to stop drawing guidelines once mouse is up
isInVerticalCenter = isInHorizontalCenter = null;
canvas.renderAll();
});
}
function initAligningGuidelines(canvas) {
var ctx = canvas.getSelectionContext(),
aligningLineOffset = 100, //5,
aligningLineMargin = 8, //4,
aligningLineWidth = 1.5, //1.5,
aligningLineColor = 'rgba(50,96,171,1)',
viewportTransform,
zoom = 1;
function drawVerticalLine(coords) {
drawLine(
coords.x + 0.5,
coords.y1 > coords.y2 ? coords.y2 : coords.y1,
coords.x + 0.5,
coords.y2 > coords.y1 ? coords.y2 : coords.y1);
}
function drawHorizontalLine(coords) {
drawLine(
coords.x1 > coords.x2 ? coords.x2 : coords.x1,
coords.y + 0.5,
coords.x2 > coords.x1 ? coords.x2 : coords.x1,
coords.y + 0.5);
}
//function drawLine(x1, y1, x2, y2) {
// ctx.save();
// ctx.lineWidth = aligningLineWidth;
// ctx.strokeStyle = aligningLineColor;
// ctx.beginPath();
// ctx.moveTo(((x1+viewportTransform[4])*zoom), ((y1+viewportTransform[5])*zoom));
// ctx.lineTo(((x2+viewportTransform[4])*zoom), ((y2+viewportTransform[5])*zoom));
// ctx.stroke();
// ctx.restore();
//}
function drawLine(x1, y1, x2, y2) {
var originXY = fabric.util.transformPoint(new fabric.Point(x1, y1), canvas.viewportTransform),
dimensions = fabric.util.transformPoint(new fabric.Point(x2, y2),canvas.viewportTransform);
ctx.save()
ctx.lineWidth = aligningLineWidth
ctx.strokeStyle = aligningLineColor
ctx.beginPath()
ctx.moveTo(
( (originXY.x ) ),
( (originXY.y ) )
)
ctx.lineTo(
( (dimensions.x ) ),
( (dimensions.y ) )
)
ctx.stroke()
ctx.restore()
}
function isInRange(value1, value2) {
value1 = Math.round(value1);
value2 = Math.round(value2);
for (var i = value1 - aligningLineMargin, len = value1 + aligningLineMargin; i <= len; i++) {
if (i === value2) {
return true;
}
}
return false;
}
var verticalLines = [],
horizontalLines = [];
canvas.on('mouse:down', function () {
viewportTransform = canvas.viewportTransform;
zoom = canvas.getZoom();
});
canvas.on('object:moving', function(e) {
var activeObject = e.target,
canvasObjects = canvas.getObjects(),
activeObjectCenter = activeObject.getCenterPoint(),
activeObjectLeft = activeObjectCenter.x,
activeObjectTop = activeObjectCenter.y,
activeObjectBoundingRect = activeObject.getBoundingRect(),
activeObjectHeight = activeObjectBoundingRect.height / viewportTransform[3],
activeObjectWidth = activeObjectBoundingRect.width / viewportTransform[0],
horizontalInTheRange = false,
verticalInTheRange = false,
transform = canvas._currentTransform;
if (!transform) return;
// It should be trivial to DRY this up by encapsulating (repeating) creation of x1, x2, y1, and y2 into functions,
// but we're not doing it here for perf. reasons -- as this a function that's invoked on every mouse move
for (var i = canvasObjects.length; i--; ) {
if (canvasObjects[i] === activeObject) continue;
if (canvasObjects[i].mmkLayerType === 'layerVectorEditor') continue; // skip vector editor layers
var objectCenter = canvasObjects[i].getCenterPoint(),
objectLeft = objectCenter.x,
objectTop = objectCenter.y,
objectBoundingRect = canvasObjects[i].getBoundingRect(),
objectHeight = objectBoundingRect.height / viewportTransform[3],
objectWidth = objectBoundingRect.width / viewportTransform[0];
// snap by the horizontal center line
if (isInRange(objectLeft, activeObjectLeft)) {
verticalInTheRange = true;
verticalLines.push({
x: objectLeft,
y1: (objectTop < activeObjectTop)
? (objectTop - objectHeight / 2 - aligningLineOffset)
: (objectTop + objectHeight / 2 + aligningLineOffset),
y2: (activeObjectTop > objectTop)
? (activeObjectTop + activeObjectHeight / 2 + aligningLineOffset)
: (activeObjectTop - activeObjectHeight / 2 - aligningLineOffset)
});
//console.log('is in horzontal range');
activeObject.setPositionByOrigin(new fabric.Point(objectLeft, activeObjectTop), 'center', 'center');
}
// snap by the left edge
if (isInRange(objectLeft - objectWidth / 2, activeObjectLeft - activeObjectWidth / 2)) {
verticalInTheRange = true;
verticalLines.push({
x: objectLeft - objectWidth / 2,
y1: (objectTop < activeObjectTop)
? (objectTop - objectHeight / 2 - aligningLineOffset)
: (objectTop + objectHeight / 2 + aligningLineOffset),
y2: (activeObjectTop > objectTop)
? (activeObjectTop + activeObjectHeight / 2 + aligningLineOffset)
: (activeObjectTop - activeObjectHeight / 2 - aligningLineOffset)
});
activeObject.setPositionByOrigin(new fabric.Point(objectLeft - objectWidth / 2 + activeObjectWidth / 2, activeObjectTop), 'center', 'center');
}
// snap by the right edge
if (isInRange(objectLeft + objectWidth / 2, activeObjectLeft + activeObjectWidth / 2)) {
verticalInTheRange = true;
verticalLines.push({
x: objectLeft + objectWidth / 2,
y1: (objectTop < activeObjectTop)
? (objectTop - objectHeight / 2 - aligningLineOffset)
: (objectTop + objectHeight / 2 + aligningLineOffset),
y2: (activeObjectTop > objectTop)
? (activeObjectTop + activeObjectHeight / 2 + aligningLineOffset)
: (activeObjectTop - activeObjectHeight / 2 - aligningLineOffset)
});
activeObject.setPositionByOrigin(new fabric.Point(objectLeft + objectWidth / 2 - activeObjectWidth / 2, activeObjectTop), 'center', 'center');
}
// snap by the vertical center line
if (isInRange(objectTop, activeObjectTop)) {
horizontalInTheRange = true;
horizontalLines.push({
y: objectTop,
x1: (objectLeft < activeObjectLeft)
? (objectLeft - objectWidth / 2 - aligningLineOffset)
: (objectLeft + objectWidth / 2 + aligningLineOffset),
x2: (activeObjectLeft > objectLeft)
? (activeObjectLeft + activeObjectWidth / 2 + aligningLineOffset)
: (activeObjectLeft - activeObjectWidth / 2 - aligningLineOffset)
});
activeObject.setPositionByOrigin(new fabric.Point(activeObjectLeft, objectTop), 'center', 'center');
}
// snap by the top edge
if (isInRange(objectTop - objectHeight / 2, activeObjectTop - activeObjectHeight / 2)) {
horizontalInTheRange = true;
horizontalLines.push({
y: objectTop - objectHeight / 2,
x1: (objectLeft < activeObjectLeft)
? (objectLeft - objectWidth / 2 - aligningLineOffset)
: (objectLeft + objectWidth / 2 + aligningLineOffset),
x2: (activeObjectLeft > objectLeft)
? (activeObjectLeft + activeObjectWidth / 2 + aligningLineOffset)
: (activeObjectLeft - activeObjectWidth / 2 - aligningLineOffset)
});
activeObject.setPositionByOrigin(new fabric.Point(activeObjectLeft, objectTop - objectHeight / 2 + activeObjectHeight / 2), 'center', 'center');
}
// snap by the bottom edge
if (isInRange(objectTop + objectHeight / 2, activeObjectTop + activeObjectHeight / 2)) {
horizontalInTheRange = true;
horizontalLines.push({
y: objectTop + objectHeight / 2,
x1: (objectLeft < activeObjectLeft)
? (objectLeft - objectWidth / 2 - aligningLineOffset)
: (objectLeft + objectWidth / 2 + aligningLineOffset),
x2: (activeObjectLeft > objectLeft)
? (activeObjectLeft + activeObjectWidth / 2 + aligningLineOffset)
: (activeObjectLeft - activeObjectWidth / 2 - aligningLineOffset)
});
activeObject.setPositionByOrigin(new fabric.Point(activeObjectLeft, objectTop + objectHeight / 2 - activeObjectHeight / 2), 'center', 'center');
}
}
if (!horizontalInTheRange) {
horizontalLines.length = 0;
}
if (!verticalInTheRange) {
verticalLines.length = 0;
}
});
canvas.on('before:render', function() {
//canvas.clearContext(canvas.contextTop);
const ct = canvas.contextTop;
if(ct) { canvas.clearContext(ct); }
});
canvas.on('after:render', function() {
for (var i = verticalLines.length; i--; ) {
drawVerticalLine(verticalLines[i]);
}
for (var i = horizontalLines.length; i--; ) {
drawHorizontalLine(horizontalLines[i]);
}
verticalLines.length = horizontalLines.length = 0;
});
canvas.on('mouse:up', function() {
verticalLines.length = horizontalLines.length = 0;
canvas.renderAll();
});
}
// * MOVE OBJ FUNCTIONS * //
function moveObj(direction)
{
var obj = canvas.getActiveObject();
if(obj)
{
switch (direction)
{
case 'left': obj.set('left',parseInt(obj.get('left')) - 1); break;
case 'right': obj.set('left',parseInt(obj.get('left')) + 1); break;
case 'up': obj.set('top',parseInt(obj.get('top')) - 1); break;
case 'down': obj.set('top',parseInt(obj.get('top')) + 1); break;
case 'rotate':
if(obj.get('angle') < 90) { obj.set({'angle':90}); centerObjHV(); }
else if(obj.get('angle') < 180) { obj.set({'angle':180}); centerObjHV(); }
else if(obj.get('angle') < 270) { obj.set({'angle':270}); centerObjHV(); }
else if(obj.get('angle') < 360) { obj.set({'angle':0}); centerObjHV(); }
break;
case 'flipx': obj.set('flipX',!obj.flipX); break;
case 'flipy': obj.set('flipY',!obj.flipY); break;
case 'moveObjBack': if(canvas.getObjects().indexOf(obj) > 2) { obj.sendBackwards(); } break;
case 'moveObjFront': obj.bringForward(); break;
case 'moveObjToFront': obj.bringToFront(); break;
}
obj.setCoords();
updateObjControls('func_moveObj');
canvas.renderAll();
}
}
function centerObjHV () { var obj = canvas.getActiveObject(); if(obj) { obj.viewportCenter(); obj.setCoords(); updateObjControls('func_centerObjHV'); canvas.renderAll(); }}
function centerObjH () { var obj = canvas.getActiveObject(); if(obj) { obj.viewportCenterH(); obj.setCoords(); updateObjControls('func_centerObjH'); canvas.renderAll(); }}
function centerObjV () { var obj = canvas.getActiveObject(); if(obj) { obj.viewportCenterV(); obj.setCoords(); updateObjControls('func_centerObjV'); canvas.renderAll(); }}
function removeObj ()
{
var obj = canvas.getActiveObject();
if(obj)
{
if(obj.mmkLayerType=='layerComponent')
{
var componentList = getComponents();
componentList[obj.mmkObjectID]--;
setComponents(componentList);
}
else if(obj.mmkLayerType == 'layerVectorResult' || obj.mmkLayerType == 'layerVectorEditor')
{
// search for corresponding sibling
var sibling = obj.mmkLayerType=='layerVectorResult' ? 'layerVectorEditor': 'layerVectorResult';
var siblingObj = 0;
for (var i=0; i < canvas.getObjects().length; i++)
{ if(canvas.item(i).mmkLayerType == sibling && canvas.item(i).mmkLayerUniqueID == obj.mmkLayerUniqueID) { siblingObj=i; break; }}
if(siblingObj!=0) { canvas.remove(canvas.item(siblingObj)); }
if(obj.mmkSerienText)
{
$('#serientext').hide();
$('#TXTMODE').val(0);
$('#TXTDATA').val('');
$('#MENGE').prop('readonly', false);
}
}
canvas.remove(obj); hideObjControls(); calculateSign('removeObj()',0); canvas.renderAll();
}
}
function fillObj(color)
{
var obj = canvas.getActiveObject();
if(obj.mmkLayerType=='layerCutForm') {}
else if(obj.mmkLayerType=='layerFixation') {}
else
{
if(obj.get('type')=='image')
{
obj.filters.push(filterBlendColor(color));
obj.set({fill: color, mmkLayerFill: 1});
obj.applyFilters();
canvas.renderAll();
}
else
{
// FILL UN- / GROUPED OBJECTS
obj.set({ mmkLayerFill: 1 });
fillObjWithColor(obj, color);
}
register_mmkLayerFill(obj);
/** FIND VECTOR EDITOR OR VECTOR RESULT FILL SIBLING */
if(obj.mmkLayerType=='layerVectorEditor' || obj.mmkLayerType=='layerVectorResult')
{
var search = obj.mmkLayerType=='layerVectorEditor' ? 'layerVectorResult' : 'layerVectorEditor';
var sibling = getVectorResultSibling(obj,search);
if(sibling!=0)
{
//console.log(sibling, canvas.item(sibling).mmkLayerType)
canvas.item(sibling).set({ mmkLayerFill: 1 });
fillObjWithColor(canvas.item(sibling), color);
register_mmkLayerFill(canvas.item(sibling));
}
}
}
obj.setCoords();
updateObjControls('func_fillObj');
canvas.renderAll();
calculateSign('fillObj()',0);
}
/** ---------------------------------------------------------------------------*/
/** RESIZE BACK */
/** ---------------------------------------------------------------------------*/
function resizeBack(x,y)
{
//console.log(x,y);
// DESELECT ALL OBJECTS
canvas.discardActiveObject();
hideObjControls();
// TYPECAST
x = parseFloat(x); //Only for full digits
y = parseFloat(y);
// IF SIZE > x CHANGE MASSSTAB
var max = SIGN.dimMax.split('x');
var min = SIGN.dimMin.split('x');
// CHECK MAX/MIN DIM (value now checked by input events)
var dimError=0;
if($("#DIMMODE1").is(':checked'))
{
//console.log('X/Y: ' + max[0] + ',' + min[0] + ', ' +x)
//if(x > parseInt(max[0])) { x=max[0]; $('#WIDTH').val(max[0]+'.0'); dimError=1; $('#errorbarFix').html('Der Artikel kann maximal ' +max[0]+' x '+max[1]+ ' mm groß sein! Die Größe wurde zurück gesetzt.
'); }
//if(x < parseInt(min[0])) { x=min[0]; $('#WIDTH').val(min[0]+'.0'); dimError=1; $('#errorbarFix').html('Der Artikel muss mindestens ' +min[0]+' x '+min[1]+ ' mm groß sein! Die Größe wurde zurück gesetzt.
'); }
//if(y > parseInt(max[1])) { y=max[1]; $('#HEIGHT').val(max[1]+'.0'); dimError=1; $('#errorbarFix').html('Der Artikel kann maximal ' +max[0]+' x '+max[1]+ ' mm groß sein! Die Größe wurde zurück gesetzt.
'); }
//if(y < parseInt(min[1])) { y=min[1]; $('#HEIGHT').val(min[1]+'.0'); dimError=1; $('#errorbarFix').html('Der Artikel muss mindestens ' +min[0]+' x '+min[1]+ ' mm groß sein! Die Größe wurde zurück gesetzt.
'); }
if(x > parseInt(max[0])) { x=max[0]; $('#WIDTH').val(max[0]); dimError=1; $('#errorbarFix').html('Der Artikel kann maximal ' +max[0]+' x '+max[1]+ ' mm groß sein! Die Größe wurde zurück gesetzt.
'); }
if(x < parseInt(min[0])) { x=min[0]; $('#WIDTH').val(min[0]); dimError=1; $('#errorbarFix').html('Der Artikel muss mindestens ' +min[0]+' x '+min[1]+ ' mm groß sein! Die Größe wurde zurück gesetzt.
'); }
if(y > parseInt(max[1])) { y=max[1]; $('#HEIGHT').val(max[1]); dimError=1; $('#errorbarFix').html('Der Artikel kann maximal ' +max[0]+' x '+max[1]+ ' mm groß sein! Die Größe wurde zurück gesetzt.
'); }
if(y < parseInt(min[1])) { y=min[1]; $('#HEIGHT').val(min[1]); dimError=1; $('#errorbarFix').html('Der Artikel muss mindestens ' +min[0]+' x '+min[1]+ ' mm groß sein! Die Größe wurde zurück gesetzt.
'); }
}
// XAXIS CORRECT SIZE
xAxisDim= parseFloat(x).toFixed(1);
yAxisDim= parseFloat(y).toFixed(1);
// EMMIT MAX RATIO
//var cw=SIGN.maxWidth; //728; // CANVAS MAX WIDTH
//var cy=470; // CANVAS MAX HEIGHT
var xRatio = parseFloat(SIGN.maxWidth/x);
var yRatio = parseFloat(SIGN.maxHeight/y); //.toPrecision(5);
// GET SCALE DIM
if(x > y && (xRatio*y) < SIGN.maxHeight)
{
SIGN.scaleFac=xRatio;
x = SIGN.maxWidth;
y = y * SIGN.scaleFac;
}
else
{
SIGN.scaleFac=yRatio;
y = SIGN.maxHeight;
x = x * SIGN.scaleFac;
}
//console.log('SIGNscaleFac: ' +SIGN.scaleFac);
if(parseInt(SIGN.scaleFac)==0) { //
//var scaleDec=SIGN.scaleFac.replace(/0\./g,'');
//SIGN.scale='1:'+parseInt(scaleDec);
if(SIGN.scaleFac==xRatio) { SIGN.scale='1:'+ Math.round(xAxisDim/SIGN.maxWidth); }
else { SIGN.scale='1:'+ Math.round(yAxisDim/SIGN.maxHeight); }
}
else { SIGN.scale=parseInt(SIGN.scaleFac)+':1'; }
// RESIZE OBJECT BY TYPE
var obj = canvas.item(0);
var oldobj = canvas.item(0);
var borderobj = canvas.item(1);
var type = obj.get('type');
// RECALC BORDER
calculateBorder($('#BORDERID').val());
//LOG = true;
LOG && console.log('ResizeBack to: '+ x+ 'x' +y+ ' ('+SIGN.scaleFac+' / ' + SIGN.scale+')');
switch(type)
{
case 'rect':
obj.set({ width: x, height: y});
borderobj.set({ width: x-SIGN.borderDistance, height: y - SIGN.borderDistance });
if($('#FORMDATA').val()=='rounded')
{
obj.set({rx:parseInt(SIGN.cornerRadius * SIGN.scaleFac), ry: parseInt(SIGN.cornerRadius * SIGN.scaleFac)});
borderobj.set({rx:parseInt(SIGN.cornerRadius * SIGN.scaleFac), ry: parseInt(SIGN.cornerRadius * SIGN.scaleFac)});
}
break;
case 'circle' : console.log('circle not detected'); break;
case 'ellipse': obj.set({ rx: parseInt(x/2), ry: parseInt(y/2) });
borderobj.set({ rx: parseInt((x-SIGN.borderDistance)/2), ry: parseInt((y-SIGN.borderDistance)/2) });
break;
case 'path':
case 'group':
case 'path-group':
obj.set({ scaleY: parseInt(y)/obj.height, scaleX: parseInt(x)/obj.width });
borderobj.set({ scaleY: parseInt(y-SIGN.borderDistance)/borderobj.height, scaleX: parseInt(x-SIGN.borderDistance)/borderobj.width });
break;
}
// REDRAW BORDEROBJ
redrawBorder(borderobj);
// CALC OBJECTS
obj.setCoords();
borderobj.setCoords();
// SET DIMENSION DISPLAY (inactive)
var xCorr = 20;
$('#xDim').css('width', x+'px');
$('#xDim').css('left', xCorr+'px');
$('#xDimValue').html('Breite: '+xAxisDim+' mm, H\u00F6he: '+yAxisDim+' mm (Ma\u00DFstab '+ SIGN.scale+')');
// SET SCALE
SIGN.width=x;
SIGN.height=y;
// SET SIGN DIM IN WK
$('#wkSignDim').html($('#WIDTH').val() + ' x ' + $('#HEIGHT').val() + ' mm');
// SHOW ERROR
if(dimError==1) { $('#errorbarFix').show().delay(SIGN.errorDelay).fadeOut('slow'); }
// CHECK IF FIXATION IS POSSIBLE
delay(function() {
var startdelay = timer(0);
checkFixation();
restoreComponents();
redrawStayOnTopLayer();
calculateSign('resizeBack()',0);
var tdiffdelay = timer(startdelay);
LOG && console.log('Delayed Object Loader in resizeBack() (25 ms) loads in: ' +tdiffdelay);
}, 25);
canvas.calcOffset();
canvas.renderAll();
setCanvasZoomInit('ResizeBack');
}
/** ---------------------------------------------------------------------------*/
/** CHANGE BACK COLOR */
/** ---------------------------------------------------------------------------*/
function changeBackColor(obj,color,bgcolor,name,id,bgimage,groupid, mustCalculateSign)
{
// DESELECT ALL OBJECTS
canvas.discardActiveObject();
hideObjControls();
// SET BG PATTERN ON SIGN
if(bgimage.length>0) { loadBackgroundPattern(bgimage); }
else { canvas.item(0).set({'fill':bgcolor}); }
// SET FOREGROUND FOR ALL OBJECTS EXCEPT FILL COLORS IN FILLABLE MODE
for(x=2; x WAS SENT BACK TO ZERO
if(!borderid) { borderid=$('#BORDERID').val(); } // LATE SIZE
// CHECK IF BORDER IS ALLOWED (FOR NOW <4 show)
if(id>=4) // SFORMID
{
borderid=1;
SIGN.border=0;
$('#BORDERID').val(1);
$('#BORDER').val('none');
$("#SLIDERBORDERS button").each(function()
{
if($(this).attr('id')!='sborder1')
{
var ltid = $(this).attr('id');
ltid =ltid.replace('sborder','');
$('#sborderListItem' + ltid).fadeOut(1000);
}
});
}
else
{
$("#SLIDERBORDERS button").each(function()
{
if($(this).attr('id')!='sborder1')
{
var ltid = $(this).attr('id');
ltid =ltid.replace('sborder','');
$('#sborderListItem' + ltid).fadeIn(1000);
}
});
}
// SET BORDER
calculateBorder(borderid);
// alert('borderDistance: ' + SIGN.borderDistance + ' => Width/Height: ' + SIGN.border);
LOG && console.log('CreateBackgroundArea: Dim: '+ SIGN.width +' x '+SIGN.height+' ,Border: '+ SIGN.borderDistance +' x '+SIGN.borderDistance+' ,Formdata: '+formdata);
// SET NEW OBJECT
switch(formdata)
{
case 'rectangle':
var bgObj = new fabric.Rect({ width: parseInt(SIGN.width), height: parseInt(SIGN.height) });
var borderObj = new fabric.Rect({ width: parseInt(SIGN.width - SIGN.borderDistance), height: parseInt(SIGN.height - SIGN.borderDistance)});
break;
case 'rounded':
//var bgObj = new fabric.Rect({ rx: 10, ry: 10, width: parseInt(SIGN.width), height: parseInt(SIGN.height)});
//var borderObj = new fabric.Rect({ rx: 10, ry: 10, width: parseInt(SIGN.width - SIGN.borderDistance), height: parseInt(SIGN.height - SIGN.borderDistance)});
var bgObj = new fabric.Rect({ rx: parseInt(SIGN.cornerRadius * SIGN.scaleFac), ry: parseInt(3 * SIGN.scaleFac), width: parseInt(SIGN.width), height: parseInt(SIGN.height)});
var borderObj = new fabric.Rect({ rx: parseInt(SIGN.cornerRadius * SIGN.scaleFac), ry: parseInt(3 * SIGN.scaleFac), width: parseInt(SIGN.width - SIGN.borderDistance), height: parseInt(SIGN.height - SIGN.borderDistance)});
break;
case 'ellipse' :
var bgObj = new fabric.Ellipse({ rx: parseInt(SIGN.width/2), ry: parseInt(SIGN.height/2)});
var borderObj = new fabric.Ellipse({ rx: parseInt((SIGN.width-SIGN.borderDistance)/2), ry: parseInt((SIGN.height- SIGN.borderDistance)/2)});
break;
default:
var bgObj = new fabric.Path(formdata);
bgObj.set({ top: parseInt(SIGN.height/2),
left: parseInt(SIGN.width/2),
scaleY: parseInt(SIGN.height)/bgObj.height,
scaleX: parseInt(SIGN.width)/bgObj.width,
});
var borderObj = new fabric.Path(formdata);
borderObj.set({ top: parseInt(SIGN.height-SIGN.borderDistance)/2,
left: parseInt(SIGN.width-SIGN.borderDistance)/2,
scaleY: parseInt(SIGN.height-((SIGN.borderDistance*2)))/borderObj.height,
scaleX: parseInt(SIGN.width-((SIGN.borderDistance*2)))/borderObj.width,
centeredScaling: 1
});
break;
}
// REDRAW SIGN + BORDEROBJ
bgObj.set({ left: 0, top: 0, originX: 'left', originY: 'top', fill: SIGN.bgcolor, shadow: 'rgba(0,0,0,0.5) 0 0 15px', strokeWidth: 0, stroke: SIGN.color,
absolutePositioned: true, clip_id: 'bgObj', objectCaching: false });
// bgObj.set({ left: 10, top: 10, originX: 'left', originY: 'top', fill: SIGN.bgcolor, shadow: 'rgba(0,0,0,0.5) 0 0 15px', strokeWidth: 0, stroke: SIGN.color,
// absolutePositioned: true, clip_id: 'bgObj', objectCaching: false });
redrawBorder(borderObj);
if($('#COLORBGIMAGE').val().length > 0) { loadBackgroundPattern($('#COLORBGIMAGE').val()); }
// SET OBJECT
$('#FORM').val(form);
$('#FORMID').val(id);
$('#FORMDATA').val(formdata);
// SELECT BaCKGROUND + BORDER SELECTORS
$("#SLIDERFORMS button").each(function() { $(this).removeClass('gradSelect').addClass('grad'); });
$("#sform"+id).addClass('gradSelect');
$("#SLIDERBORDERS button").each(function() { $(this).removeClass('gradSelect').addClass('grad'); });
$("#sborder"+borderid).addClass('gradSelect');
// PLACE OBJECTS
canvas.add(bgObj) //... sent to back last added
canvas.add(borderObj)
bgObj.selectable = false;
bgObj.setCoords();
//bgObj.viewportCenter();
borderObj.selectable = false;
borderObj.setCoords();
//borderObj.viewportCenter();
canvas.sendToBack(borderObj); // ==> set LVL Border to Level 0 canvas.item(1)
canvas.sendToBack(bgObj); // ==> set To Level 0 canvas.item(0)
// CHECK IF FIXATION IS POSSIBLE
$.when(checkFixation()).done(function(ev) {
//checkFixation();
canvas.calcOffset();
canvas.renderAll();
if(mustCalculateSign==1) { calculateSign('createBackgroundArea()',0); }
});
// CLIPPING TO OBJECT
if($('#PRODUCTID').val()=='37')
{
bgLayer=bgObj;
//canvas.item(2).set({clipPath: bgLayer, clip_target: 'bgLayer'});
}
else
{
SIGN.clipping ? bgLayer=bgObj : bgLayer=null;
//canvas.item(2).set({clipPath: bgLayer, clip_target: 'bgLayer'});
}
for(x=2; x ');
//canvas.discardActiveObject();
canvas.calcOffset();
canvas.renderAll.bind(canvas);
$('#canvasBox').css({'background':"url(https://schilderstyle.de/konfigurator/xkonf/overlay/garden_bg.jpg)",'background-size':'cover'}); $('#xDim').css('border-top-color','#ccc'); //$('#xDimValue').css('color','#555'); });
$('#miniViewPanel').css({'background':'url(https://schilderstyle.de/konfigurator/xkonf/overlay/garden_bg.jpg)','background-size':'cover'});
}
}
/** ---------------------------------------------------------------------------*/
/** */
/** TEXT BASED FUNCTIONS */
/** */
/** ---------------------------------------------------------------------------*/
function chooseText(font)
{
$('#textFontSelector').val(font);
$('.textFontSelector').val(font);
$('#textCutFontSelector').val(font);
$('.textCutFontSelector').val(font);
formatText("font");
$('#textFontList').hide();
$('.textFontList').hide();
$('#textCutFontList').hide();
$('.textCutFontList').hide();
}
async function addText()
{
// TEXT ADD
var size = parseInt(canvas.item(0).width/12);
var font = $('#textFontSelector').val();
var text = 'Hier Text eingeben';
// CHECK FOR VECTORIZABLE FONTS
var vectorFont = {}
for (var key in SIGN.vectorizableFonts)
{
if(font == key) { vectorFont= SIGN.vectorizableFonts[key]; break; }
}
if(Object.entries(vectorFont).length!==0) { font= vectorFont['cssName']; } // i.e. SST_Montserrat
if(text)
{
var txtPlace = new fabric.IText(text, {
left: 100,
top: 100,
fill: SIGN.color,
fontSize: size,
fontFamily: font,
textAlign: 'center',
//charSpacing: '0', // has to be string, for effect?
caching: false,
clipPath: bgLayer,
clip_target: 'bgLayer',
//originX: 'center',
//originY: 'center',
centeredScaling: true,
centeredRotation: true,
lockScalingFlip: true,
});
extendObject(txtPlace, 'mmkLayerUniqueID', '');
formatObjControls(txtPlace,1);
canvas.add(txtPlace);
canvas.setActiveObject(txtPlace);
txtPlace.setCoords();
canvas.renderAll();
$('#textAdder').prop("disabled",true);
calculateSign('addText()',0);
$('#textAdder').prop("disabled",false);
centerObjHV();
updateObjControls('obj_modified_addText'); // ensures vectorization of fonts
if(SIGN.closeMenuAfterAdd===true) { closeMenues(); }
} else { alert('Bitte geben Sie einen Text ein'); }
}
async function addCutText()
{
// TEXT ADD
var size = parseInt(canvas.item(0).width/12);
var font = $('#textCutFontSelector').val();
var text= 'Hier Text eingeben';
// CHECK FOR VECTORIZABLE FONTS
var vectorFont = {}
var defaultVectorFont = {}
//console.log(SIGN.vectorizableFonts);
var x=0;
for (var key in SIGN.vectorizableFonts)
{
if(Object.entries(defaultVectorFont).length==0) { if(SIGN.vectorizableFonts[key]['cutform']==1) { defaultVectorFont= SIGN.vectorizableFonts[key]; }}
if(font == key) { vectorFont= SIGN.vectorizableFonts[key]; break; }
x++;
}
if(Object.entries(vectorFont).length!==0) { font= vectorFont['cssName']; } else { font = defaultVectorFont['cssName']; } // TO DEFAULT
if(text)
{
var cutTxtPlace = new fabric.IText(text, {
left: 100,
top: 100,
//fill: SIGN.color,
fill: SIGN.cutFormColor,
fontSize: size,
fontFamily: font,
textAlign: 'center',
caching: false,
clipPath: bgLayer,
stroke: SIGN.cutFormStrokeColor,
strokeDashArray: [SIGN.cutFormStrokeDashWidth,SIGN.cutFormStrokeDashWidth], //SIGN.cutFormStrokeArray,
strokeWidth: SIGN.cutFormStrokeWidth,
centeredScaling: 1,
fill: SIGN.cutFormColor,
clip_target: 'bgLayer',
centeredScaling: true,
centeredRotation: true,
lockScalingFlip: true,
});
extendObject(cutTxtPlace, 'mmkRenderAsCutForm', true); // BECAUSE MMKLAYERTYPE IS VECTOR EDITOR
extendObject(cutTxtPlace, 'mmkLayerUniqueID', '');
formatObjControls(cutTxtPlace,1);
canvas.add(cutTxtPlace);
canvas.setActiveObject(cutTxtPlace);
centerObjHV();
cutTxtPlace.setCoords();
canvas.renderAll();
$('#cutTextAdder').prop("disabled",true);
calculateSign('addCutText()',0);
$('#cutTextAdder').prop("disabled",false);
updateObjControls('obj_modified_addText'); // ensures vectorization of fonts
if(SIGN.closeMenuAfterAdd===true) { closeMenues(); }
} else { alert('Bitte geben Sie einen Text ein'); }
}
function addSerienText(text)
{
// TEXT ADD
var font = $('#textFontSelector').val();
// CHECK FOR VECTORIZABLE FONTS
var vectorFont = {}
var defaultVectorFont = {}
var x=0;
for (var key in SIGN.vectorizableFonts)
{
if(Object.entries(defaultVectorFont).length==0) { if(SIGN.vectorizableFonts[key]['cutform']==1) { defaultVectorFont= SIGN.vectorizableFonts[key]; }}
if(font == key) { vectorFont= SIGN.vectorizableFonts[key]; break; }
x++;
}
if(Object.entries(vectorFont).length!==0) { font= vectorFont['cssName']; } else { font = defaultVectorFont['cssName']; } // TO DEFAULT
if(text)
{
var dpParam = getSerienTextDisplay(text);
text = dpParam[0];
var signs = dpParam[1];
var txtPlace = new fabric.IText(text, {
left: 100,
top: 100,
fill: SIGN.color,
//fontSize: size,
fontFamily: font,
textAlign: 'center',
caching: false,
editable: false,
clipPath: bgLayer,
clip_target: 'bgLayer',
centeredScaling: true,
lockScalingFlip: true,
});
//console.log(txtPlace.textLines.length);
// CALC BEST WIDTH (RESPECT HEIGHT) - 20%;
var ratio = (canvas.item(0).width / txtPlace.width) - (canvas.item(0).width / txtPlace.width * 0.2)
txtPlace.set({'scaleX' : ratio, 'scaleY': ratio });
extendObject(txtPlace, 'mmkSerienText', true); // BECAUSE MMKLAYERTYPE IS VECTOR EDITOR
extendObject(txtPlace, 'mmkLayerUniqueID', '');
formatObjControls(txtPlace,1);
canvas.add(txtPlace);
canvas.setActiveObject(txtPlace);
centerObjHV();
updateObjControls('obj_modified_addText'); // ensures vectorization of fonts
canvas.renderAll();
calculateSign('addSerienText()',0);
return signs;
} else { alert('Bitte geben Sie einen Text ein'); }
}
function updateSerienText(text,obj)
{
if(text)
{
var serienTextData = getSerienTextDisplay(text); // last sign, signs
obj.set({'text': serienTextData[0]});
obj.setCoords();
canvas.renderAll();
calculateSign('updateSerienText()',0);
return serienTextData[1];
}
}
function getSerienTextDisplay(text)
{
/* count signs, return maxlines and st field with longest string */
var retText='';
text=String(text);
var rows = text.split('|');
rows.pop(); //newlines?
var signs=rows.length/5;
// CHECK MAX ZEILE
var maxZeilen = 1;
var x=1;
$.each(rows, function(index,val)
{
if(val.length>0 && maxZeilen < x) { maxZeilen=x; }
x++; if(x==6) { x=1; }
});
// CHECK LONGEST STRING
var renewTxtField = 0;
var longestStrLength = 0;
var longestTxtField='';
x=1;
$.each(rows, function(index,val)
{
if(x==1) { retText=''; renewTxtField=0; }
if(val.length > longestStrLength) { longestStrLength = val.length; renewTxtField = 1; }
if(x<=maxZeilen) { retText = x==1 ? retText + val : retText + '\n'+val; }
x++; if(x==6) { x=1; if(renewTxtField==1) { longestTxtField = retText; }}
});
LOG && console.log('getSerienTextReturn:' + retText + ' MaxZeilen:' + maxZeilen + ' Signs: ' + signs);
return [longestTxtField,signs];
}
function refreshSerienTextForm(text)
{
var rows = text.split('|');
var ix = 0;
var row = new Array();
for(i=0; i < rows.length; i++)
{
row[ix]=rows[i]
ix++;
if(ix==5) {
if(i==4) { $('#noSerienText').hide(); }
$("#TDATATABLE").append('Entwurf: | | | | | | | |
'); //add input box
ix=0; row= new Array();
}
}
// REBUILD UNDEFINDED VALUES
if(ix!=0)
{
if(typeof row[0] === 'undefined') { row[0]=''; }
if(typeof row[1] === 'undefined') { row[1]=''; }
if(typeof row[2] === 'undefined') { row[2]=''; }
if(typeof row[3] === 'undefined') { row[3]=''; }
if(typeof row[4] === 'undefined') { row[4]=''; }
$("#TDATATABLE").append('Entwurf: | | | | | | | |
'); //add input box
}
}
async function formatText(mode)
{
var obj = canvas.getActiveObject();
var vectorFont = {};
/** CHECK FOR VECTOR FONT */
for (var key in SIGN.vectorizableFonts)
{
if(obj.mmkRenderAsCutForm)
{
if($('#textCutFontSelector').val() == key) { vectorFont= SIGN.vectorizableFonts[key]; break;}
}
else
{
if($('#textFontSelector').val() == key) { vectorFont= SIGN.vectorizableFonts[key]; break;}
}
}
/** CHECK EDITING ON VECTOR RESULT... */
if(obj.mmkLayerType=='layerVectorResult')
{
//console.log('activate sibling');
var sibling = getVectorResultSibling(obj,'layerVectorEditor');
if(sibling!=0)
{
canvas.discardActiveObject();
obj = canvas.item(sibling)
//console.log(obj);
//console.log(vectorFont);
//console.log($('#textFontSelector').val());
obj.set({'fontFamily':$('#textFontSelector').val()}); // SET FONT FOR NONE VECTORS
await editVectorizedFont(obj);
//console.log('vectorization done');
}
}
switch(mode)
{
case 'bold' : $('.textBold').each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); if(obj.fontWeight=='normal') { obj.set({'fontWeight':'bold'}); $('.textBold').addClass('gradSelect'); } else { obj.set({'fontWeight':'normal'}); } break;
case 'italic' : $('.textItalic').each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); if(obj.fontStyle =='normal') { obj.set({'fontStyle':'italic'}); $('.textItalic').addClass('gradSelect'); } else { obj.set({'fontStyle':'normal'}); } break;
case 'underline': $('.textUnderline').each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); if(obj.underline == false) { obj.set({'underline': true}); $('.textUnderline').addClass('gradSelect'); } else { obj.set({'underline':false}); } break;
case 'left' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textLeft').addClass('gradSelect'); obj.set({'textAlign':'left'}); break; //,'originX':'left','left': canvas.item(0).left }); break;
case 'center' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textCenter').addClass('gradSelect'); obj.set({'textAlign':'center'}); break; //,'originX':'center','left': (canvas.item(0).width/2)
case 'right' : $(".ttformat").each(function() { $(this).removeClass('gradSelect').addClass('grad'); }); $('.textRight').addClass('gradSelect'); obj.set({'textAlign':'right'}); break; //, 'originX':'right', 'left': canvas.item(0).left + canvas.item(0).width }); console.log('PosX: ' +urx[0]); break; //,'originX': 'right', 'left': obj.left + obj.width}); break;
case 'font' :
/** CHECK FOR VECTOR FONT */
//for (var key in SIGN.vectorizableFonts)
//{
// if($('#textFontSelector').val() == key) { vectorFont= SIGN.vectorizableFonts[key]; break;}
// }
if(Object.entries(vectorFont).length !== 0)
{
obj.set({'fontFamily': vectorFont['cssName'] }); // i.e. SST_Montserrat
}
else
{
// REMOVE VECTORIZED FONTS ON CHANGE ... needs Fallback if only vectorFonts available
if(obj.mmkLayerType=='layerVectorEditor')
{
var sibling = getVectorResultSibling(obj,'layerVectorResult');
if(sibling!=0)
{
canvas.remove(canvas.item(sibling));
}
}
obj.set({'fontFamily':$('#textFontSelector').val(), 'mmkLayerType':''});
extendObject(obj,'mmkLayerType', '');
canvas.requestRenderAll();
}
break;
}
/** (RE)SET BOLD / ITALIC ACTIONS FOR VECTOR FONTS */
//if($('#textFontSelector').val()=='Montserrat')
if(Object.entries(vectorFont).length !== 0) /** BUGGY IF NOT ALL FONTS AVAILABLE */
{
// RESET
$('.textBold').each(function() { $(this).removeClass('gradSelect').addClass('grad'); });
$('.textItalic').each(function() { $(this).removeClass('gradSelect').addClass('grad'); });
// set correct font family
if(obj.fontWeight == 'normal' && obj.fontStyle == 'italic' && vectorFont['italic']==1)
{
obj.set({'fontFamily' : vectorFont['cssName'] +'Italic' });
obj.set({'fontStyle':'italic'});
obj.set({'fontWeight':'normal'});
$('.textItalic').addClass('gradSelect');
}
else if(obj.fontWeight == 'bold' && obj.fontStyle == 'normal' && vectorFont['bold']==1)
{
obj.set({'fontFamily' : vectorFont['cssName'] +'Bold' });
obj.set({'fontStyle':'normal'});
obj.set({'fontWeight':'bold'});
$('.textBold').addClass('gradSelect');
}
else if(obj.fontWeight == 'bold' && obj.fontStyle == 'italic' && vectorFont['bold']==1 && vectorFont['italic']==1)
{
obj.set({'fontFamily' : vectorFont['cssName'] +'BoldItalic' });
obj.set({'fontStyle':'italic'});
obj.set({'fontWeight':'bold'});
$('.textItalic').addClass('gradSelect');
$('.textBold').addClass('gradSelect');
}
else // Default (Regular)
{
obj.set({'fontFamily' : vectorFont['cssName']});
obj.set({'fontWeight':'normal'});
obj.set({'fontStyle':'normal'});
}
//fabric.util.clearFabricFontCache();
//canvas.requestRenderAll();
//console.log('setCorrectFontFamily: ' + obj.fontFamily, obj.fontWeight, obj.fontStyle);
// Nasty width Hack to ensure refresh
obj.set({'width': obj.get('width') + 0.000001,'fontFamily': obj.fontFamily});
fabric.util.clearFabricFontCache();
obj.setCoords();
canvas.requestRenderAll();
}
//console.log('After: ' + obj.get('fontFamily') +',' + obj.get('fontWeight') +',' + obj.get('fontStyle'));
fabric.util.clearFabricFontCache();
obj.setCoords();
canvas.renderAll();
calculateSign('formatText()',0);
refreshMiniView();
updateObjControls('obj_modified'); // cause no event was fired on add
}
/** ---------------------------------------------------------------------------*/
/** IMAGE BASED FUNCTIONS */
/** ---------------------------------------------------------------------------*/
function addImage(image)
{
var im = image.split('|');
image = im[0];
var resolution = parseInt(im[1]);
//console.log(im);
var ext = image.substr( (image.lastIndexOf('.') +1) ).toLowerCase();
var scRatio = canvas.item(0).get('width') >= canvas.item(0).get('height') ? 0:1;
var scFac = canvas.item(0).get('width') >= canvas.item(0).get('height') ? (canvas.item(0).get('height')/canvas.item(0).get('width')) : (canvas.item(0).get('width')/canvas.item(0).get('height'));
var width = scRatio == 0 ? parseInt(canvas.item(0).get('width')/2) : parseInt(canvas.item(0).get('width') * scFac);
var height = scRatio == 1 ? parseInt(canvas.item(0).get('height')/2) : parseInt(canvas.item(0).get('height') * scFac);
if(ext=='jpg' || ext=='jpeg')
{
fabric.Image.fromURL('../'+image, function(obj)
{
formatObjControls(obj,1);
obj.scaleToWidth(width);
obj.scaleToHeight(height);
canvas.add(obj);
//obj.set({centeredScaling: 1, crossOrigin: "anonymous"});
obj.set({centeredScaling: 1, crossOrigin: "anonymous", clipPath: bgLayer, clip_target: 'bgLayer'});
canvas.renderAll.bind(canvas);
canvas.setActiveObject(obj);
/** IS FULL COLOR DIGITALDRUCK FALSE ? **/
if($('#ENGRAVEMETHOD option:selected').val()!=8)
{
// SET FILTERS
obj.filters.push(filterRemoveWhite());
obj.filters.push(filterBlendColor(SIGN.color));
obj.applyFilters()
canvas.renderAll();
obj.set({ mmkTrueColor: 0 });
obj.set({ mmkImageResolution: resolution });
}
else
{ obj.set({ mmkTrueColor: 1 });
obj.set({ mmkImageResolution: resolution });
}
register_mmkTrueColor(obj);
register_mmkImageResolution(obj);
centerObjHV();
calculateSign('addImage(jpg)',0);
});
}
if(ext=='svg')
{
image = image.replace('\.\.\/\.\.\/','');
image = image.replace('\.\.\/','');
var x=0; var pobj='';
fabric.loadSVGFromURL('https://schilderstyle.de/konfigurator/' + image, function(objects, options)
{
var obj = fabric.util.groupSVGElements(objects, options);
formatObjControls(obj,1);
obj.set({ centeredScaling: 1, clipPath: bgLayer, clip_target: 'bgLayer'});
/** IS FULL COLOR DIGITALDRUCK FALSE ? **/
if($('#ENGRAVEMETHOD option:selected').val()!=8) // ONLY IF NOT TRUE COLOR
{
fillObjWithColor(obj, SIGN.color);
obj.set({ mmkTrueColor: 0 });
}
else
{ obj.set({ mmkTrueColor: 1 }); }
register_mmkTrueColor(obj);
obj.scaleToWidth(width);
obj.scaleToHeight(height);
canvas.add(obj);
canvas.renderAll.bind(canvas);
canvas.setActiveObject(obj);
centerObjHV();
calculateSign('addImage(svg)',0);
console.log('adding svg');
});
}
canvas.renderAll();
if(SIGN.closeMenuAfterAdd===true) { closeMenues(); }
}
function filterRemoveWhite()
{
var filter = new fabric.Image.filters.RemoveColor({
color:'#FFFFFF',
distance: 0.5
});
return filter;
}
function showBlackWhiteControl(obj, value)
{
setBlackWhiteControlPos();
$('.blackWhiteControl').show();
$('.blackWhiteDistance').val(obj.filters[0]['distance']);
}
function hideBlackWhiteControl()
{
$('.blackWhiteControl').hide();
}
function setBlackWhiteControlPos()
{
var obj = canvas.getActiveObject();
if(obj)
{
var yOffset = $(window).width() < 1024 ? 140 : 72; // Responsive
var bwcX = Math.round(obj.oCoords.tr.x + 6);
var bwcY = Math.round(obj.oCoords.tr.y + yOffset);
$('.blackWhiteControl').css({'left': bwcX + 'px', 'top': bwcY +'px'});
}
}
function setBlackWhiteFilter()
{
var obj = canvas.getActiveObject();
if(obj)
{
//console.log(parseFloat($('.blackWhiteDistance').val()));
obj.filters[0]['distance'] = parseFloat($('.blackWhiteDistance').val());
obj.applyFilters();
canvas.renderAll();
}
}
function filterBlendColor(color)
{
var filter = new fabric.Image.filters.BlendColor({
color: color,
mode: 'tint',
alpha: 1
});
return filter;
}
function fillObjWithColor(obj, color)
{
/** DETERMINES IF GROUP FILL OR PATH FILL */
if (obj.type == 'group' || obj.type == 'path-group')
{ var group = obj; for (var i=0; i < group.getObjects().length; i++)
{
if(obj.mmkLayerType=='layerBarcode')
{
if(obj.mmkBarcodeInverted==1)
{
if(i <= 1) { group.item(i).set({'fill': color }); }
else { group.item(i).set({'fill': SIGN.bgcolor }); }
}
else
{ group.item(i).set({'fill':color}); }
}
else
{
group.item(i).set({'fill':color});
}
//fillObjSelector(obj,color); // no longer needed?
}
}
else { obj.set({'fill':color}); fillObjSelector(obj,color); }
}
function fillObjSelector(obj,color)
{
//if(obj.mmkLayerType=='layerSerienText') {} // || obj.mmkLayerFill==='undefined' || obj.mmkLayerFill=='') {
if(obj.mmkSerienText) {}
else { /* obj.set({'borderColor':color, 'cornerColor':color}); */ }
}
function selectImageCat(id)
{
$(".imageBlock").each(function() { $(this).hide(); });
$('.imgCategories').each(function() { $(this).removeClass('gradSelect').addClass('grad'); })
$('#imgCategory'+id).addClass('gradSelect')
$("#ib"+id).show();
}
/** ---------------------------------------------------------------------------*/
/** */
/** CUT FORMS BASED FUNCTIONS */
/** */
/** ---------------------------------------------------------------------------*/
function addCutForm(type)
{
switch(type)
{
case 'rectangle':
var bgObj = new fabric.Rect({
top: 100,
left: 0,
//radius: 5,
width: 20,
height: 20,
stroke: SIGN.cutFormStrokeColor,
strokeDashArray: [SIGN.cutFormStrokeDashWidth,SIGN.cutFormStrokeDashWidth], //SIGN.cutFormStrokeArray,
strokeWidth: SIGN.cutFormStrokeWidth,
centeredScaling: 1,
fill: SIGN.cutFormColor,
mmkLayerType: 'layerCutForm'
});
break;
case 'ellipse':
var bgObj = new fabric.Circle({
top: 100,
left: 0,
radius: 10,
stroke: SIGN.cutFormStrokeColor,
strokeDashArray: [SIGN.cutFormStrokeDashWidth,SIGN.cutFormStrokeDashWidth],
strokeWidth: SIGN.cutFormStrokeWidth,
centeredScaling: 1,
fill: SIGN.cutFormColor,
mmkLayerType: 'layerCutForm'
});
break;
case 'triangle':
var bgObj = new fabric.Triangle({
width: 20,
height: 20,
top: 100,
left: 0,
stroke: SIGN.cutFormStrokeColor,
strokeDashArray: [SIGN.cutFormStrokeDashWidth,SIGN.cutFormStrokeDashWidth],
strokeWidth: SIGN.cutFormStrokeWidth,
centeredScaling: 1,
fill: SIGN.cutFormColor,
mmkLayerType: 'layerCutForm'
});
break;
default:
var bgObj = new fabric.Path(type);
bgObj.set({ top: 100,
left: 0,
scaleY: 0.2,
scaleX: 0.2,
stroke: SIGN.cutFormStrokeColor,
strokeDashArray: [SIGN.cutFormStrokeDashWidth,SIGN.cutFormStrokeDashWidth],
strokeWidth: SIGN.cutFormStrokeWidth,
centeredScaling: 1,
fill: SIGN.cutFormColor,
mmkLayerType: 'layerCutForm'
});
}
if(bgObj)
{
bgObj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
mmkLayerType: this.mmkLayerType
});
};
})(bgObj.toObject);
formatObjControls(bgObj,1);
canvas.add(bgObj).renderAll();
canvas.setActiveObject(bgObj);
centerObjHV();
}
calculateSign('addCutForm()',0);
}
function restoreCutFormBorder(obj)
{
strokeWidth = SIGN.cutFormStrokeWidth/obj.get('scaleX'); //SIGN.scaleFac;
//console.log('StrokeWidth: ' +strokeWidth + ', ObjScale: ' + obj.get('scaleX')+ ', ObjDIM: ' + obj.get('width') +',' + obj.get('height') );
if(obj.mmkRenderAsCutForm && obj.type=='group')
{
var group = obj;
for (var i=0; i < group.getObjects().length; i++)
{
group.item(i).set({'stroke': SIGN.cutFormStrokeColor,'strokeWidth':strokeWidth, strokeDashArray: [5/obj.get('scaleX'),5/obj.get('scaleX')]});
}
}
else
{
obj.set({'stroke': SIGN.cutFormStrokeColor,'strokeWidth':strokeWidth, strokeDashArray: [5/obj.get('scaleX'),5/obj.get('scaleX')]});
}
}
function addImageCutForm(image)
{
var im = image.split('|');
image = im[0];
var resolution = parseInt(im[1]);
var ext = image.substr( (image.lastIndexOf('.') +1) ).toLowerCase();
var scRatio = canvas.item(0).get('width') >= canvas.item(0).get('height') ? 0:1;
var scFac = canvas.item(0).get('width') >= canvas.item(0).get('height') ? (canvas.item(0).get('height')/canvas.item(0).get('width')) : (canvas.item(0).get('width')/canvas.item(0).get('height'));
var width = scRatio == 0 ? parseInt(canvas.item(0).get('width')/2) : parseInt(canvas.item(0).get('width') * scFac);
var height = scRatio == 1 ? parseInt(canvas.item(0).get('height')/2) : parseInt(canvas.item(0).get('height') * scFac);
if(ext=='svg')
{
image = image.replace('\.\.\/','');
var x=0; var pobj='';
fabric.loadSVGFromURL('https://schilderstyle.de/konfigurator/' + image, function(objects, options)
{
//var svg = fabric.util.groupSVGElements(objects, options);
if(objects[0].type!='image')
{
//console.log('CutFormType: '+ objects[0].type);
//console.log(objects);
//if(obj.type=='group') { // isolate first path
// obj = obj._objects[0]; }
obj = objects[0];
obj.set({'centeredScaling': 1,'fill': SIGN.cutFormColor, clipPath: bgLayer, clip_target: 'bgLayer'});
obj.scaleToWidth(width);
obj.scaleToHeight(height);
obj.set({ mmkLayerType: 'layerCutForm' });
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
mmkLayerType: this.mmkLayerType
});
};
})(obj.toObject);
formatObjControls(obj,1);
canvas.add(obj);
//restoreCutFormBorder(obj);
canvas.calcOffset();
canvas.renderAll.bind(canvas);
canvas.setActiveObject(obj);
centerObjHV();
calculateSign('addImageCutForm(svg)',0);
}
});
}
if(SIGN.closeMenuAfterAdd===true) { closeMenues(); }
}
/** ---------------------------------------------------------------------------*/
/** FIXATION BASED FUNCTIONS */
/** ---------------------------------------------------------------------------*/
function checkFixation(fixid)
{
// GET WIDTH IN MM
var sw=0;
var sy=0;
var dimmode=0;
var allowedFixations= new Array("1");
if($('#DIMMODE0').is(':checked'))
{
var dim = $('#DIMSTD').val().split('x');
sw=dim[0];
sy=dim[1];
dimmode=0;
}
if($('#DIMMODE1').is(':checked'))
{
sw=$('#WIDTH').val();
sy=$('#HEIGHT').val()
dimmode=1;
}
// CHECK IF SELECTED FORM HAS SELECTED FIXID + SIGNFORM + IN DIM ELSE => NONE
var fixOK=0;
for(var i = 0; i < FIXDATA.length; i++)
{
// CHECK CURRENT SIGN FORM / FX / SIZE OK
if($('#FORMID').val() == parseInt(FIXDATA[i][0]) &&
$('#FIXATIONID').val() == parseInt(FIXDATA[i][1]) &&
parseFloat(sw) > parseFloat(FIXDATA[i][2]) &&
parseFloat(sy) > parseFloat(FIXDATA[i][3]))
{
fixOK=1;
}
// CHECK IF IS IN ALLOWED FIXATIONS VIA SIZE
if($('#FORMID').val() == parseInt(FIXDATA[i][0]) &&
parseFloat(sw) > parseFloat(FIXDATA[i][2]) &&
parseFloat(sy) > parseFloat(FIXDATA[i][3]))
{
allowedFixations.push(FIXDATA[i][1]);
}
}
// HIDE ALL UNUSABLE FIXATIONS
$(".fixations").each(function()
{
fxid=this.id.replace('fixationBlock','');
if(in_array(fxid , allowedFixations)!= -1){
$('#fixationBlock'+fxid).show();
}
else
{
$('#fixationBlock'+fxid).hide();
}
});
if(fixOK==1)
{
var fixation = parseInt($('#FIXATIONID').val());
}
else
{ var fixation=1; $('#FIXATIONID').val(1); $('#FIXATIONNAME').val('Keine') }
switch(fixation)
{
case 1: addFixation(1,'','Keine',0); break;
case 2: addFixation(2,'','1 x Bohrung',0); break;
case 3: addFixation(3,'','2 x Bohrung',0); break;
case 4: addFixation(4,'','4 x Bohrung',0); break;
case 5: addFixation(5,'','Selbstkleb. Folie',0); break;
case 6: addFixation(6,'','Magnetstreifen',0); break;
case 7: addFixation(7,'ws','Abstandshalter',0); break;
case 8: addFixation(8,'','1 x Kugelkette',0); break;
case 9: addFixation(9,'screw','Schrauben inkl. Dübel'); break;
case 10: addFixation(10,'','S-Haken',0); break;
case 11: addFixation(11,'','Schlüsselring',0); break;
case 12: addFixation(12,'','Magnethalter für Namenschilder',0); break;
case 13: addFixation(13,'','Sicherheitsnadel',0); break;
case 14: addFixation(14,'','Clip',0); break;
case 15: addFixation(15,'','Krokodilklemme',0); break;
case 18: addFixation(18,'','Saugnapf',0); break;
case 23: addFixation(23,'wsgold','Abstandshalter Gold',0); break;
case 26: addFixation(26,'wsgold','Abstandshalter Gold',0); break;
}
}
function addFixation(id,overlay,name,directCall)
{
// REMOVE EXISTING FIXATIONS
var fixID=new Array();
for(x=0; x " +fixObjCount +"=> ID: " + x );
}
/* CHECKEN OB DEFAULT VALUES ODER RESTORE (LOAD SIGN) ODER DIMENSION FEHLER -> RESTORE*/
var FX = { fxERROR: 0 };
switch(mode)
{
case 1: FX = fixationCalculateBounds(fixObj,1,[tx,ty,sw,sh]); break;
case 2: FX = fixationCalculateBounds(fixObj,2,[tx,ty,sw,sh]); break;
case 4: FX = fixationCalculateBounds(fixObj,4,[tx,ty,sw,sh]); break;
}
/* SET FIXATION PANELS */
showFixationPanels(mode);
/* SHOW ERROR MESSAGES AND STUFF */
if(FX.fxERROR==1) {
$('#errorbarFix').html('Mindestabstand zu gering. Mindestabstand einer Bohrung zum Rand = 3mm. Der Mindestdurchmesser = 2mm.');
$('#errorbarFix').show().delay(SIGN.errorDelay).fadeOut('slow');
}
/* SETTING NEW FIXATION POS */
var fxDiameter = parseFloat($('#fixDiameter').val()); //.toFixed(2);
var fxRadius = parseFloat($('#fixDiameter').val() / 2 ); //.toFixed(2);
switch(mode)
{
case 1:
fixObj[0].set({top: ty + parseFloat(SIGN.scaleFac * FX.fxV), radius: parseFloat(SIGN.scaleFac * fxRadius)});
canvas.setActiveObject(fixObj[0]); centerObjH(); fixObj[0].setCoords(); // fixObj[0].selectable = false;
break;
case 2:
fixObj[0].set({left: tx + parseFloat(SIGN.scaleFac * FX.fxH1), radius: parseFloat(SIGN.scaleFac * fxRadius)});
fixObj[1].set({left: tx + parseFloat(SIGN.scaleFac * FX.fxH2), radius: parseFloat(SIGN.scaleFac * fxRadius)});
canvas.setActiveObject(fixObj[0]); centerObjV(); fixObj[0].setCoords(); //fixObj[0].selectable = false;
canvas.setActiveObject(fixObj[1]); centerObjV(); fixObj[1].setCoords(); //fixObj[1].selectable = false;
break;
case 4:
fixObj[0].set({top: ty + parseFloat(SIGN.scaleFac * FX.fxVT), left: tx + parseFloat(SIGN.scaleFac * FX.fxHL), radius: parseFloat(SIGN.scaleFac * fxRadius)});
fixObj[1].set({top: ty + parseFloat(SIGN.scaleFac * FX.fxVT), left: tx + parseFloat(SIGN.scaleFac * FX.fxHR), radius: parseFloat(SIGN.scaleFac * fxRadius)});
fixObj[2].set({top: ty + parseFloat(SIGN.scaleFac * FX.fxVB), left: tx + parseFloat(SIGN.scaleFac * FX.fxHL), radius: parseFloat(SIGN.scaleFac * fxRadius)});
fixObj[3].set({top: ty + parseFloat(SIGN.scaleFac * FX.fxVB), left: tx + parseFloat(SIGN.scaleFac * FX.fxHR), radius: parseFloat(SIGN.scaleFac * fxRadius)});
canvas.setActiveObject(fixObj[0]); fixObj[0].setCoords();
canvas.setActiveObject(fixObj[1]); fixObj[1].setCoords();
canvas.setActiveObject(fixObj[2]); fixObj[2].setCoords();
canvas.setActiveObject(fixObj[3]); fixObj[3].setCoords();
break;
}
/* REMOVE INVALID OBJECTS FROM LAYERS */
//console.log(invalidFixObj);
for (var x = 0; x < invalidFixObj.length; ++x)
{
var layer= invalidFixObj[x] - x;
canvas.remove(canvas.item(layer));
}
canvas.discardActiveObject();
canvas.renderAll();
}
function fixationCalculateBounds(objList,mode,coords)
{
var FX = { fxV: 0, fxH1: 0, fxH2: 0, fxHL: 0, fxHR: 0, fxVT: 0, fxVB: 0, fxERROR: 0 };
var realSW = SIGN.width/SIGN.scaleFac;
var realSH = SIGN.height/SIGN.scaleFac;
var realSMHorizontal = (SIGN.width/2/SIGN.scaleFac);
var realSMVertikal = (SIGN.height/2/SIGN.scaleFac);
switch(mode)
{
case 1:
checkVal = $('#fixVertikal1').val();
if(checkVal.length==0)
{
$('#fixVertikal1').val(SIGN.fixationDefaultDistance);
$('#fixDiameter').val(SIGN.fixationDefaultDiameter);
}
else
{
// CALC BY INPUT
FX.fxV = parseFloat( parseFloat( $('#fixVertikal1').val() ) - ($('#fixDiameter').val()/2));
// CHECK OUTTA BOUNDS
if((FX.fxV >=3 && FX.fxV <= (realSH - 3)) && ($('#fixDiameter').val() < (realSW - 6)) && $('#fixDiameter').val() >= 2) { }
else
{ FX.fxERROR=1;
//restoreFixationByJSON(objList);
$('#fixVertikal1').val(SIGN.fixationDefaultDistance);
$('#fixDiameter').val(SIGN.fixationDefaultDiameter);
}
LOG && console.log('RESTORE NEEDED ---> Height: ' + realSH + ', Width: ' + realSW+ ', FX.fxV (Top): ' + FX.fxV);
}
FX.fxV = parseFloat( parseFloat( $('#fixVertikal1').val() ) - ($('#fixDiameter').val()/2));
break;
case 2:
checkVal = $('#fixHorizontal2').val();
if(checkVal.length==0)
{
var horizontalDist = (realSW - (SIGN.fixationDefaultDistance * 2));
$('#fixHorizontal2').val(horizontalDist);
$('#fixDiameter').val(SIGN.fixationDefaultDiameter);
}
else
{
// CALC BY INPUT
FX.fxH1 = parseFloat(realSMHorizontal - ($('#fixDiameter').val()/2) - ($('#fixHorizontal2').val()/2));
FX.fxH2 = parseFloat(realSMHorizontal + ($('#fixHorizontal2').val()/2) - ($('#fixDiameter').val()/2));
// CHECK OUTTA BOUNDS
if((FX.fxH1 >=3 && FX.fxH2 <= (realSW - 3)) && (parseFloat($('#fixHorizontal2').val()) >= (parseFloat($('#fixDiameter').val()) + 3)) && ($('#fixDiameter').val() < (realSH - 6)) && $('#fixDiameter').val() >= 2) { }
else
{ FX.fxERROR=1;
//restoreFixationByJSON(objList);
var horizontalDist = (realSW - (SIGN.fixationDefaultDistance * 2));
$('#fixHorizontal2').val(horizontalDist);
$('#fixDiameter').val(SIGN.fixationDefaultDiameter);
}
}
FX.fxH1 = parseFloat(realSMHorizontal - ($('#fixDiameter').val()/2) - ($('#fixHorizontal2').val()/2));
FX.fxH2 = parseFloat(realSMHorizontal + ($('#fixHorizontal2').val()/2) - ($('#fixDiameter').val()/2));
break;
case 4:
checkVal = $('#fixHorizontal4').val() + $('#fixVertikal4').val();
if(checkVal.length==0)
{
var horizontalDist = (realSW - (SIGN.fixationDefaultDistance * 2));
var verticalDist = (realSH - (SIGN.fixationDefaultDistance * 2));
$('#fixHorizontal4').val(horizontalDist);
$('#fixVertikal4').val(verticalDist);
$('#fixDiameter').val(SIGN.fixationDefaultDiameter);
}
else
{
// CALC BY INPUT
FX.fxHL = parseFloat(realSMHorizontal - ($('#fixDiameter').val()/2) - ($('#fixHorizontal4').val()/2));
FX.fxHR = parseFloat(realSMHorizontal + ($('#fixHorizontal4').val()/2) - ($('#fixDiameter').val()/2));
FX.fxVT = parseFloat(realSMVertikal - ($('#fixDiameter').val()/2) - ($('#fixVertikal4').val()/2));
FX.fxVB = parseFloat(realSMVertikal + ($('#fixVertikal4').val()/2) - ($('#fixDiameter').val()/2));
// CHECK OUTTA BOUNDS
if((FX.fxHL >=3 && FX.fxHR <= (realSW - 3)) && (FX.fxVT >=3 && FX.fxVB <= (realSH - 3)) &&
(parseFloat($('#fixHorizontal4').val()) >= (parseFloat($('#fixDiameter').val()) + 3)) &&
(parseFloat($('#fixVertikal4').val()) >= (parseFloat($('#fixDiameter').val()) + 3)) &&
($('#fixDiameter').val() < (realSH - 6)) && $('#fixDiameter').val() >= 2)
{ }
else
{
FX.fxERROR=1;
//restoreFixationByJSON(objList);
var horizontalDist = (realSW - (SIGN.fixationDefaultDistance * 2));
var verticalDist = (realSH - (SIGN.fixationDefaultDistance * 2));
$('#fixHorizontal4').val(horizontalDist);
$('#fixVertikal4').val(verticalDist);
$('#fixDiameter').val(SIGN.fixationDefaultDiameter);
}
}
FX.fxHL = parseFloat(realSMHorizontal - ($('#fixDiameter').val()/2) - ($('#fixHorizontal4').val()/2));
FX.fxHR = parseFloat(realSMHorizontal + ($('#fixHorizontal4').val()/2) - ($('#fixDiameter').val()/2));
FX.fxVT = parseFloat(realSMVertikal - ($('#fixDiameter').val()/2) - ($('#fixVertikal4').val()/2));
FX.fxVB = parseFloat(realSMVertikal + ($('#fixVertikal4').val()/2) - ($('#fixDiameter').val()/2));
LOG && console.log('4REAL fxHL: ' + FX.fxHL + ', fxHR: ' + FX.fxHR + ', fxVT: ' + FX.fxVT + ', fxVB: ' + FX.fxVB + ', Diameter: ' + $('#fixDiameter').val() + ', fixHoriz: ' + $('#fixHorizontal4').val() + ', fixVerti: ' + $('#fixVertikal4').val() +', realSMHorizontal: ' + realSMHorizontal +', realSMVertikal: ' + realSMVertikal);
break;
}
/** Wenn SIGN.width == $('#WIDTH').val() ist wird mit skalierten Werden gearbeitet. Hierbei darf keine Fehlerausgabe erfolgen (Nur bei Reload)**/
if(SIGN.width==parseFloat($('#WIDTH').val())) { FX.fxERROR=0; }
return FX;
}
/** ---------------------------------------------------------------------------*/
/** COMPONENT BASED FUNCTIONS */
/** ---------------------------------------------------------------------------*/
function restoreComponents()
{
var components;
// GET ALLOWED IDS
var componentList = getComponents();
var ALLOWED_IDS = new Array();
var REMOVE_IDS = new Array();
$('.components').each(function()
{
item = parseInt($(this).attr('id').replace('componentsBlock',''));
ALLOWED_IDS.push(item);
});
LOG && console.log('RESTORING COMPONENTS');
for(x=2; x 19
stroke: fstrc,
strokeWidth: fstrw,
fill: SIGN.cutFormColor,
originX : 'center',
originY : 'center',
selectable: true,
mmkLayerType: 'layerCompFixation',
});
register_mmkLayerType(obj01);
canvas.setActiveObject(obj01); //centerObjHV(); // obj01.selectable = false;
// Overlay
var posLeftWS = parseFloat (4.5 * SIGN.scaleFac);
var posTopWS = parseFloat (4.5 * SIGN.scaleFac);
var dpimage = '';
switch(id)
{
case 1: dpimage = 'klingelknopf_ns.png'; break;
case 2: dpimage = 'klingelknopf_led_blau_ns.png'; break;
case 3: dpimage = 'klingelknopf_led_rot_ns.png'; break;
case 4: dpimage = 'klingelknopf_led_gelb_ns.png'; break;
case 5: dpimage = 'klingelknopf_led_gruen_ns.png'; break;
case 6: dpimage = 'klingelknopf_led_weiss_ns.png'; break;
}
//var obj02 = null;
fabric.Image.fromURL("https://schilderstyle.de/konfigurator/xkonf/components/" + dpimage, function(obj)
{
var obj02 = obj.set({ scaleX: scaleSCW, scaleY: scaleSCH, originX : 'center', originY : 'center', opacity: 1});
var groupObj = new fabric.Group([obj01,obj02],
{ 'left': 0,
'top': 0,
'selectable': true,
'hasControls': true,
'lockScalingX': true,
'lockScalingY': true,
mmkLayerType: 'layerComponent',
mmkObjectID: id
})
formatObjControls(groupObj,1);
canvas.add(groupObj);
groupObj.setCoords();
groupObj.viewportCenter();
canvas.setActiveObject(groupObj);
register_mmkLayerType(groupObj);
register_mmkObjectID(groupObj);
});
// ADD TO COMPONENTLIST
if((id in componentList)) { componentList[id]++; } else { componentList[id]=1; }
break;
case 7:
// Calc Overlay
var sizeOVW = parseFloat(40); //22
var sizeOVH = parseFloat(40); //22
var scaleSCW = parseFloat(sizeOVW / (267/SIGN.scaleFac));
var scaleSCH = parseFloat(sizeOVH / (267/SIGN.scaleFac));
// Bohrung
var obj01 = new fabric.Circle({
radius: parseFloat(SIGN.scaleFac * 8), // 9.5 -> 19
stroke: fstrc,
strokeWidth: fstrw,
fill: SIGN.cutFormColor,
originX : 'center',
originY : 'center',
selectable: true,
mmkLayerType: 'layerCompFixation',
});
register_mmkLayerType(obj01);
canvas.setActiveObject(obj01); //centerObjHV(); // obj01.selectable = false;
// Overlay
var posLeftWS = parseFloat (4.5 * SIGN.scaleFac);
var posTopWS = parseFloat (4.5 * SIGN.scaleFac);
var dpimage = 'notstop.png';
//var obj02 = null;
fabric.Image.fromURL("https://schilderstyle.de/konfigurator/xkonf/components/" + dpimage, function(obj)
{
var obj02 = obj.set({ scaleX: scaleSCW, scaleY: scaleSCH, originX : 'center', originY : 'center', opacity: 1});
var groupObj = new fabric.Group([obj01,obj02],
{ 'left': 0,
'top': 0,
'selectable': true,
'hasControls': true,
'lockScalingX': true,
'lockScalingY': true,
mmkLayerType: 'layerComponent',
mmkObjectID: id
})
formatObjControls(groupObj,1);
canvas.add(groupObj);
groupObj.setCoords();
groupObj.viewportCenter();
canvas.setActiveObject(groupObj);
register_mmkLayerType(groupObj);
register_mmkObjectID(groupObj);
});
// ADD TO COMPONENTLIST
if((id in componentList)) { componentList[id]++; } else { componentList[id]=1; }
break;
case 8:
// Calc Overlay
var sizeOVW = parseFloat(142);
var sizeOVH = parseFloat(142);
// Bohrung
var obj01 = new fabric.Circle({
radius: parseFloat(SIGN.scaleFac * 4), // 9.5 -> 19
stroke: fstrc,
strokeWidth: fstrw,
fill: SIGN.cutFormColor,
originX : 'center',
originY : 'center',
selectable: true,
mmkLayerType: 'layerCompFixation',
});
register_mmkLayerType(obj01);
canvas.setActiveObject(obj01); //centerObjHV(); // obj01.selectable = false;
// Overlay
var dpimage = 'xkonf/components/funkuhr.svg';
fabric.loadSVGFromURL('https://schilderstyle.de/konfigurator/' + dpimage, function(objects, options)
{
var obj = fabric.util.groupSVGElements(objects, options);
var obj02 = obj.set({ scaleX: sizeOVW / (obj.get('width') / SIGN.scaleFac), scaleY: sizeOVH / (obj.get('height') / SIGN.scaleFac), originX : 'center', originY : 'center', opacity: 1});
var groupObj = new fabric.Group([obj01,obj02],
{ 'left': 0,
'top': 0,
'selectable': true,
'hasControls': true,
'lockScalingX': true,
'lockScalingY': true,
mmkLayerType: 'layerComponent',
mmkObjectID: id
})
formatObjControls(groupObj,1);
canvas.add(groupObj);
groupObj.setCoords();
groupObj.viewportCenter();
canvas.setActiveObject(groupObj);
register_mmkLayerType(groupObj);
register_mmkObjectID(groupObj);
});
// ADD TO COMPONENTLIST
if((id in componentList)) { componentList[id]++; } else { componentList[id]=1; }
break;
}
// DESELECT ALL
canvas.discardActiveObject();
hideObjControls();
canvas.renderAll();
/** ADD + SET COMPONENT LIST **/
setComponents(componentList)
// only needed on standalone not needed
updateObjControls('func_Addcomponent');
if(directCall==1) { calculateSign('addComponent()'); }
if(SIGN.closeMenuAfterAdd===true) { closeMenues(); }
}
function getComponents()
{
var compList = {};
if($('#COMPONENTSLIST').val().length > 0)
{
var compPairs = $('#COMPONENTSLIST').val().split(';').filter(item => item);
for(var key in compPairs)
{
var compItems = compPairs[key].split('|');
compList[compItems[0]]=compItems[1];
}
}
return compList;
}
function setComponents(componentList)
{
var components = '';
for(var key in componentList)
{
item = key +'|'+componentList[key]+';'
if(componentList[key]>0)
{
components = components + item;
}
}
$('#COMPONENTSLIST').val(components);
}
/** ---------------------------------------------------------------------------*/
/** QR CODE / CODES BASED FUNCTIONS */
/** ---------------------------------------------------------------------------*/
function addBarcode(svgdata,btyp,bmode,bdata,binverted)
{
var scRatio = canvas.item(0).get('width') >= canvas.item(0).get('height') ? 0:1;
var scFac = canvas.item(0).get('width') >= canvas.item(0).get('height') ? (canvas.item(0).get('height')/canvas.item(0).get('width')) : (canvas.item(0).get('width')/canvas.item(0).get('height'));
var width = scRatio == 0 ? parseInt(canvas.item(0).get('width')/2) : parseInt(canvas.item(0).get('width') * scFac);
var height = scRatio == 1 ? parseInt(canvas.item(0).get('height')/2) : parseInt(canvas.item(0).get('height') * scFac);
var x=0; var pobj='';
//console.log(btyp);
if(btyp=='barcode')
{
// convert path to rectangle
var newSVGBarcodeData = '';
var pathCount = 0;
fabric.loadSVGFromString(svgdata, function(objects, options)
{
newSVGBarcodeData ='';
svgdata = newSVGBarcodeData;
});
//console.log(newSVGBarcodeData);
}
if(binverted==1)
{
// Fabric cant handle percentage in at least rect???
const viewBox = (/viewBox="([^"]+)"/.exec(svgdata) || '')[1];
const viewBoxArr = viewBox.split(" ");
var newSVGdataW = svgdata.replace("100%",viewBoxArr[2]);
var newSVGdataH = newSVGdataW.replace("100%",viewBoxArr[3]);
svgdata= newSVGdataH;
//console.log(svgdata);
}
fabric.loadSVGFromString(svgdata, function(objects, options)
{
var obj = fabric.util.groupSVGElements(objects, options);
obj.set({ centeredScaling: 1, clipPath: bgLayer, clip_target: 'bgLayer', mmkLayerType: 'layerBarcode', lockScalingFlip: true });
extendObject(obj, 'mmkLayerType', 'layerBarcode');
extendObject(obj, 'mmkBarcodeType', btyp);
extendObject(obj, 'mmkBarcodeMode', bmode);
extendObject(obj, 'mmkBarcodeData', bdata);
extendObject(obj, 'mmkBarcodeInverted', binverted);
register_mmkTrueColor(obj);
formatObjControls(obj,1);
/** IS FULL COLOR DIGITALDRUCK FALSE ? **/
if($('#ENGRAVEMETHOD option:selected').val()!=8) // ONLY IF NOT TRUE COLOR
{
fillObjWithColor(obj, SIGN.color);
obj.set({ mmkTrueColor: 0 });
}
else
{ obj.set({ mmkTrueColor: 1 }); }
obj.scaleToWidth(width);
obj.scaleToHeight(height);
canvas.add(obj);
canvas.renderAll.bind(canvas);
canvas.setActiveObject(obj);
centerObjHV();
//console.log(obj.toSVG());
calculateSign('addCode(svg)',0);
});
canvas.renderAll();
if(SIGN.closeMenuAfterAdd===true) { closeMenues(); }
}
function resetBarcodePanels()
{
$('.panelCodeType').each(function() { $(this).removeClass('gradSelect'); });
$('.panelCodeMode').each(function() { $(this).hide(); $(this).removeClass('gradSelect'); });
$('.selectQRCodeBlock').hide();
$('.selectBarcodeBlock').hide();
$('.selectDatamatrixBlock').hide();
}
function resetBarcodeModes(mode)
{
switch(mode)
{
case 'barcode':
$('.panelCodeType[data-type = "barcode"]').addClass('gradSelect');
$('.panelCodeMode').each(function() { if($(this).data('mode') == 'Text') { $(this).show(); }});
$('.selectBarcodeBlock').show();
$('.panelCodeMode:nth-child(2)').trigger('click');
break;
case 'datamatrix':
$('.panelCodeType[data-type = "datamatrix"]').addClass('gradSelect');
$('.panelCodeMode').each(function() { if($(this).data('mode') == 'Text') { $(this).show(); }});
$('.selectDatamatrixBlock').show();
$('.panelCodeMode:nth-child(2)').trigger('click');
break;
default:
$('.panelCodeType[data-type = "qrcode"]').addClass('gradSelect');
$('.panelCodeMode').each(function() { $(this).show(); });
$('.selectQRCodeBlock').show();
$('.panelCodeMode:first').trigger('click');
}
}
function restoreBarcode()
{
var obj = canvas.getActiveObject();
$('.scrollAreaLvl2').scrollTop(0);
$('.menuBarcodes').trigger('click');
if(obj && obj.mmkLayerType == 'layerBarcode')
{
resetBarcodePanels();
$('.panelCodeMode').each(function() { $(this).removeClass('gradSelect'); });
$('.codesDataPanel').each(function() { $(this).hide(); });
//console.log(obj.mmkBarcodeData);
var pdata = obj.mmkBarcodeData.split(';');
obj.mmkBarcodeInverted == 1 ? $('.codeInverted').prop('checked', true) : $('.codeInverted').prop('checked', false);
switch(obj.mmkBarcodeType)
{
case 'barcode': resetBarcodeModes('barcode'); break;
case 'datamatrix': resetBarcodeModes('datamatrix'); break;
default:
resetBarcodeModes('qrcode');
switch(obj.mmkBarcodeMode)
{
case 'URL':
$('.codeURL').val(pdata[0]);
$('.panelCodeMode[data-mode = "URL"]').trigger('click');
break;
case 'Text':
$('.codeText').val(pdata[0]);
$('.panelCodeMode[data-mode = "Text"]').trigger('click');
break;
case 'vCard':
$('.codeText').val(pdata[0]);
$('.panelCodeMode[data-mode = "Text"]').trigger('click');
break;
case 'WiFi':
$('.codeWiFiAuth').val(pdata[0]);
$('.codeWiFiNetwork').val(pdata[1]);
pdata[2]=='true' ? $('.codeWiFiHidden').prop('checked',true): $('.codeWiFiHidden').prop('checked',true);
$('.codeWiFiPassword').val(pdata[3]);
$('.panelCodeMode[data-mode = "WiFi"]').trigger('click');
break;
case 'EMail':
$('.codeEMailAddress').val(pdata[0]);
$('.codeEMailSubject').val(pdata[1]);
$('.codeEMailMessage').val(pdata[2]);
$('.panelCodeMode[data-mode = "EMail"]').trigger('click');
break;
case 'WhatsApp':
$('.codeWhatsAppNumber').val(pdata[0]);
$('.codeWhatsAppMessage').val(pdata[1]);
$('.panelCodeMode[data-mode = "WhatsApp"]').trigger('click');
break;
case 'SMS':
$('.codeSMSNumber').val(pdata[0]);
$('.codeSMSMessage').val(pdata[1]);
$('.panelCodeMode[data-mode = "SMS"]').trigger('click');
break;
}
}
}
}
/** ---------------------------------------------------------------------------*/
/** */
/** I/O OPERATIONS */
/** */
/** ---------------------------------------------------------------------------*/
/**
function changeMaterial(key)
{
// OPEN INFO WINDOW METHOD
$('#chgsp').val(key);
//chgWin.open();
// DIRECT METHOD
$('#chgMatForm').submit();
}
function changeStaerke(mat,strength,oldStaerke)
{
$('#chgstrsp').val(mat);
$('#chgstrpid').val(strength);
$('#chgstr').val(oldStaerke);
strWin.open();
}
*/
function changeStaerkeByColor(mat,strength,oldStaerke,colorid,colorname,colorgroupid,color,colorbg,colorbgimage,engravemethod)
{
$('#ENGRAVEMETHOD').append($("").attr("value", engravemethod).text('TESST'));
$('#ENGRAVEMETHOD').val(engravemethod);
//$('#chgstrsp').val(mat);
//$('#chgstrpid').val(strength);
//$('#chgstr').val(oldStaerke);
//document.getElementById('STAERKE').value=strength;
//$('#STAERKE option[value="'+ strength +'"]').attr('selected',true);
$('#STAERKE option[value="'+ strength +'"]').prop('selected',true);
$('#COLORID').val(colorid);
$('#COLORNAME').val(colorname);
$('#COLORGROUPID').val(colorgroupid);
$('#COLOR').val(color);
$('#COLORBG').val(colorbg);
$('#COLORBGIMAGE').val(colorbgimage);
changeMaterialJS($('#MATERIALID').val(),strength,'');
}
/**
function updateStaerke()
{
changeMaterialJS($('#MATERIALID').val(),$('#chgstrpid').val(),'');
//console.log('changeMaterialJS('+$('#MATERIALID').val()+','+$('#chgstrpid').val()+')');
//$('#chgstrsp').val(mat);
//$('#chgstrpid').val($('#chgstrpid').val());
//$('#chgstr').val(oldStaerke);
//$('#DIMSTD option:selected').val();
//console.log('NEWCHGSTRID: ' +$('#chgstrpid').val() + ', OLDCHGSTRID: ' + $('#chgstr').val() + ', STAERKE: ' + $('#STAERKE').val() + ', MATID: ' +$('#MATERIALID').val());
//alert($('#STAERKE').val()
//alert($('#MATERIALID').val() + 'Gettin ProductID...');
//$.ajax({ url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php", type: 'GET', cache: false, timeout: 30000, data: { com: 'changeProduct', id: $('#chgstrpid').val(), refID: $("#MATERIALID").val() },
// error: function(){ return true; }, //alert('error');
// success: function(cp) { window.parent.location.reload(); return true; }
// });
}
function restoreStaerke()
{
$('#STAERKE').val($('#chgstr').val());
}
*/
function resetAll()
{
$.ajax({type: "GET", url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php", cache: false, timeout: 3000, async:false, data: { com: 'resetSign' }}).done(function(cp)
{
canvas.clear();
/** ALTERNATIV ... if classic off keep sign settings else reset to defaults - WARNING*** FAST BUT EXTREMELY BUGGY *** **/
var jsonly=0;
var classic=1; var cptrim = cp.trim();
if(classic==1 && jsonly==1)
{
var mat = cptrim.split("|");
$('#MATERIALID').val(mat[0]);
$('#MATERIALNAME').val('');
$('#PRODUCTID').val(mat[1]);
$('#PRODUCTNAME').val('');
$('#DIMFREE').val('');
$('#DIMMAX').val('');
$('#DIMMIN').val('');
$('#FORMID').val('');
$('#FORM').val('');
$('#FORMDATA').val('');
$('#BORDERID').val('');
$('#COLORID').val('');
$('#COLORNAME').val('');
$('#COLORGROUPID').val('');
$('#COLOR').val('');
$('#COLORBG').val('');
$('#COLORBGIMAGE').val('');
$('#ENGRAVEMINFONTSIZE').val('');
$('#ENGRAVEFILLABLE').val('');
$('#TXTMODE').val('');
$('#TXTDATA').val('');
$('#TXTMODESIGNS').val('');
$('#FIXATIONID').val('');
$('#FIXATIONNAME').val('');
$('#OLDETEMPLATE').val('');
$('#COMPONENTSLIST').val('');
$('#STAERKE').empty();
$('#STAERKE').append($("").attr("value", mat[1]).text(mat[1]+' mm'));
$('#STAERKE option[value="'+mat[1]+'"]').prop('selected', true);
$("#DIMMODE0").prop("checked", true);
$('#DIMSTD').empty();
$('#DIMSTD').append($("").attr("value", mat[2]+'x'+mat[3]).text(mat[2]+'x'+mat[3]));
$('#DIMSTD option[value="'+mat[2]+'x'+mat[3]+'"]').prop('selected', true);
//$('#DIMSTD').val('0x0');
$('#WIDTH').val(mat[2]);
$('#HEIGHT').val(mat[3]);
changeMaterialJS($('#MATERIALID').val(),mat[1],'');
}
else if (classic==0 && jsonly==1)
{
changeMaterialJS($('#MATERIALID').val(),$('#STAERKE option:selected').val(),'');
}
else
{
/** OLD SCHOOL **/
SIGN.calculateOnUnload=0;
window.top.location.reload();
}
resetWin.close()
return true;
});
return false;
}
function loadSign(id,refID,URL)
{
// AJAX UPDATE REQUEST
// CHECK IF OLD SIGNS COULD BE LOADED
//alert(id+','+refID+','+URL);
$.ajax({ url: 'https://schilderstyle.de/konfigurator/scripts/mmk-io.php',
type: 'GET',
cache: false,
timeout: 3000,
async: false, //false,
dataType: "text",
data: {'com': 'loadSign', 'id': id, 'refID': refID},
error: function()
{
},
success: function(cs) {
if(URL.length>0) { SIGN.calculateOnUnload=0; window.top.location.href = URL; }
return true;
}
});
return false;
}
function deleteSign(id,refID)
{
$.ajax({ url: 'https://schilderstyle.de/konfigurator/scripts/mmk-io.php',
type: 'GET',
cache: false,
timeout: 3000,
async: false, //false,
data: {'com': 'deleteSign', 'id': id, 'refID': refID},
dataType:'json',
success: function(res)
{
if(res['status']=='ok')
{
delSaveWin.close()
$('.signSavesRow'+refID).html(res['data']);
}
},
error: function()
{
},
});
return false;
}
function loadUserSignList(source,page)
{
$.ajax({ url: 'https://schilderstyle.de/konfigurator/scripts/mmk-io.php',
type: 'GET',
cache: false,
timeout: 3000,
async: false, //false,
dataType: "text",
data: {'com': 'loadUserSignList', 'id': source, 'refID': page},
error: function()
{
},
success: function(cs) {
$('#userSignContent').html(cs);
return true;
}
});
return false;
}
function saveSign(id,mode)
{
var refID = '';
if(mode.length >0)
{
id = id.replace('saveMMK-','');
refID=mode;
}
$.when(calculateSign('saveSign()',1)).done(function(ev) {
$.ajax({type: "GET", url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php", data: { com: 'saveSign', id: id, refID: refID}}).done(function(cp)
{
SIGN.calculateOnUnload=0;
window.top.location.reload();
return true;
});
});
return false;
}
function loadTemplates(id,katname)
{
$.ajax({ url: 'https://schilderstyle.de/konfigurator/scripts/mmk-io.php',
type: 'GET',
cache: false,
timeout: 3000,
async: false, //false,
dataType: "text",
data: {'com': 'loadTemplates', 'id': id, 'refID': katname},
error: function()
{
},
success: function(cs) {
$('#templateContainer').html(cs);
$('#templateContainer').animate({scrollTop: 0 }, 500);
return true;
}
});
return false;
}
async function createAngebot()
{
await calculateSign('createAngebot',1).then (value =>
{
var jsondata = JSON.stringify(canvas);
$.ajax({type: "POST", url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php", data: { com: 'createAngebot','subcom': 'create' }}).done(function(ex)
{
canvas.clear();
changeMaterialJS($('#MATERIALID').val(),$('#PRODUCTID').val(),jsondata);
$('#schild').css('visibility','visible');
try { data = JSON.parse(ex);
forceDownload(data);
}
catch (e) { alert(ex); }
});
});
return false;
}
async function prepareAnfrage(img)
{
d = new Date();
ts = d.getTime();
nimg = img.replace(/timestamp\=\d+/,"timestamp="+ts);
$('.anfrageWinContent').hide();
$('.loader2').show();
anfrageWin.open();
anfrageWin.disable();
await calculateSign('prepareAnfrage',1);
$('#anfrageImage').css("background-image", "url("+nimg+")");
anfrageWin.enable();
$('.loader2').hide();
$('.anfrageWinContent').show();
//return true;
//return false;
}
function createAnfrage()
{
if($('#wdata1').val()=='' || $('#wdata2').val()=='' || $('#wdata3').val()=='' || $('#wdata4').val()=='' || $('#wdata5').is(':not(:checked)'))
{
alert('Bitte geben Sie Namen, E-Mail-Adresse, Telefonnummer, den Grund der Anfrage ein und bestätigen Sie die Bedingungen, um die Anfrage abzuschicken.');
}
else
{
var svgdata = saveImageAs('svg');
$.ajax({type: "POST", url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php", data: { com: 'createAnfrage', svgdata: svgdata[0], filelist: svgdata[1], imgscale: svgdata[2], wdata0: $('#wdata0').val(), wdata1: $('#wdata1').val(), wdata2: $('#wdata2').val(), wdata3: $('#wdata3').val(), wdata4: $('#wdata4').val(), adClickID: $('#adClickID').val() }}).done(function(cp)
{
SIGN.calculateOnUnload=0;
window.location.href= 'https://schilderstyle.de/konfigurator/2/danke/';
return true;
});
}
return false;
}
async function addSignToBasket()
{
$('.basketWinContent').hide();
$('.loader2').show();
basketWin.open();
basketWin.disable();
//$.when(calculateSign('addSignToBasket',1)).done(function(ev) {
await calculateSign('addSignToBasket',1).then(value =>
{
var jsondata = JSON.stringify(canvas);
var svgdata = saveImageAs('svg');
$.ajax({type: "POST", url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php", data: { com: 'addSignToBasket', svgdata: svgdata[0], filelist: svgdata[1], imgscale: svgdata[2] }}).done(function(ex)
{
basketWin.enable();
$('.loader2').hide();
$('.basketWinContent').show();
var items=$('.wkCircle', window.parent.document).text();
if(items) { items = parseInt(items) + 1; $('.wkCircle', window.parent.document).html('' + items + '');
if(items>0) { $('.wkCircle', window.parent.document).show(); }
}
canvas.clear();
changeMaterialJS($('#MATERIALID').val(),$('#PRODUCTID').val(),jsondata);
$('#schild').css('visibility','visible');
});
});
return false;
}
function loadURL(url) { window.top.location.href=url; }
function editVectorizedFont(obj)
{
/** FIND TEXT EDITOR SIBILING */
var textEditorLayer = getVectorResultSibling(obj,'layerVectorEditor');
if(textEditorLayer!=0)
{
/** DISABLE/HIDE VECTOR RESULT + SHOW RESULT EDITOR SIBLING */
obj.set({'opacity' : SIGN.fontVectorizeOpacity, 'selectable': false, 'evented': false});
obj.setCoords();
/** ENABLE TEXT OBJ + JUMP IN */
canvas.item(textEditorLayer).set({'opacity': 1,'selectable': true,'evented': true});
canvas.item(textEditorLayer).setCoords();
canvas.renderAll;
canvas.setActiveObject(canvas.item(textEditorLayer));
canvas.item(textEditorLayer).enterEditing();
if(obj.mmkSerienText) { } // SERIENTEXT HAS NO INLINE EDIT FUNCITONALITY
else { canvas.item(textEditorLayer).hiddenTextarea.focus(); }
}
}
function getVectorResultSibling(obj,sibling) // layerVectorEditor layerVectorResult
{
if(obj)
{
for(let x=0; x < canvas.getObjects().length; x++)
{
if(canvas.item(x).mmkLayerType == sibling && canvas.item(x).mmkLayerUniqueID == obj.mmkLayerUniqueID)
{
return x;
}
}
}
return 0;
}
function getVectorFontFamilyName(obj)
{
for (var key in SIGN.vectorizableFonts)
{
if(obj.fontFamily == SIGN.vectorizableFonts[key]['cssName'] ||
obj.fontFamily == SIGN.vectorizableFonts[key]['cssName']+'Italic' ||
obj.fontFamily == SIGN.vectorizableFonts[key]['cssName']+'Bold' ||
obj.fontFamily == SIGN.vectorizableFonts[key]['cssName']+'BoldItalic'
) { return key; break; }
}
return '';
}
async function vectorizeFont(obj,source,type)
{
//console.log('Vectorize -> Event: ' + source+ ', Type: ' + type + ', mmkLayerType: ' + obj.mmkLayerType + ', mmkLayerUniqueID: ' + obj.mmkLayerUniqueID);
//console.log(obj);
if(!type) { console.log('WARNING: no type'); }
/** VECTORIZE IF OBJECT MODIFIED */
if(source == 'obj_modified' || source== 'obj_modified_addText')// || (obj.mmkLayerType=='layerVectorEditor' && source=='text:editing:exited')) // || source=='before:selection:cleared') // || source=='text:editing:exited') // source=='selection:cleared') // || source=='selection:updated')
{
//console.log('Start vectorization...' );
/** CHECK IF TEXT OBJ BECOMES LAYER SHADOW COPYHAS UNIQUE ID */
if((!obj.mmkLayerUniqueID || obj.mmkLayerUniqueID=='') && obj.fontFamily.match('^SST_'))
{
extendObject(obj,'mmkLayerUniqueID', generateID());
}
/** SET LAYER TYPE FOR FONT IF VECTORIZABLE, ELSE RESET */
if(obj.fontFamily.match('^SST_'))
{
extendObject(obj,'mmkLayerType', 'layerVectorEditor');
}
else
{
extendObject(obj,'mmkLayerType', '');
}
var removeVectorID=new Array();
/** REMOVE VECORIZED LAYERS FOR given mmkLayerUniqueID */
for(x=0; x < canvas.getObjects().length; x++)
{
if(canvas.item(x).mmkLayerType == 'layerVectorResult' && canvas.item(x).mmkLayerUniqueID == obj.mmkLayerUniqueID) { removeVectorID.push(x);}
}
for(var x = removeVectorID.length; x--;) { canvas.remove(canvas.item(removeVectorID[x])); }
/** PRELODING FONTS */
const fonts = await preloadFonts().then(value =>
{
let font = obj.get('fontFamily');
let fontProp= {'RequestedFont' : font };
let layer = [];
if(SIGN.fonts[font]!== undefined)
{
/** LOAD VALUE AS PATH */
let txt = { topPos: 0, leftPos: 0, minLeftOffset: 9999, pathLength: 0 };
/** wenn mehrere Zeilen split by newline */
/** SANITIZE trim or something */
/** CALC NEW WIDTH / SCALE TO OBJ 1 */
var cScale = obj.scaleX;
//console.log('Font has SX/SY: ' + obj.scaleX,obj.scaleY);
obj.set({'scaleX':1, 'scaleY': 1, 'dirty': true}); // ensure scaleX,scaleY to be 1 before transform
obj.setCoords();
fabric.util.clearFabricFontCache();
fontProp['iTextObj'] = 'WIDTH/HEIGHT: ' + obj.width +', ' + obj.height + ', TOP/LEFT: ' + obj.top +', '+ obj.left + ', SX/SY: ' + obj.scaleX +', '+ obj.scaleY;
obj.textLines.forEach(function(line,i)
{
txt.topPos = i * obj.getHeightOfLine(i) * obj.scaleX; // * SIGN.scaleFac);
txt.leftOffset = 1.7;
txt.topOffset = 11;
//txt.leftPos = 0;
//txt.minLeftOffset = 0;
/** CORRECT POSITION */
txtObj = textToPath(SIGN.fonts[font], obj, line); // SIGN FONT preloaded Font
txt.topOffset = obj.getHeightOfLine(i) - txtObj['height'];
let textPath = new fabric.Path(txtObj['pathData'],
{
top: obj.top + (11 * obj.scaleX) + txt.topPos,
left: txt.leftPos,
scaleX: obj.scaleX,
scaleY: obj.scaleY,
lockScalingFlip: true,
//strokeWidth: 1,
//stroke: '#ff0000',
});
if(obj.mmkRenderAsCutForm)
{
textPath.set({ 'fill': SIGN.cutFormColor,
'stroke': SIGN.cutFormStrokeColor,
'strokeDashArray': [SIGN.cutFormStrokeDashWidth,SIGN.cutFormStrokeDashWidth], //SIGN.cutFormStrokeArray,
'strokeWidth': SIGN.cutFormStrokeWidth
});
}
else
{
obj.mmkLayerFill==1 ? textPath.set({'fill': obj.fill}) : textPath.set({'fill': SIGN.color});
}
layer.push(textPath)
txt.leftOffset = (obj.width - textPath.width) / 2 * obj.scaleX;
txt.minLeftOffset = txt.leftOffset < txt.minLeftOffset ? txt.leftOffset : txt.minLeftOffset;
/** CENTER ALL */
txt.leftPos = obj.left + txt.leftOffset;
textPath.set({'left': txt.leftPos })
textPath.setCoords();
//console.log('Zeile: ' + i + ': ' + textPath.width + ' leftPos: ' + txt.leftPos);
//console.log(txtObj);
/** NO NEED TO ADD FONT, JUST CALC AND RETURN LENGTH */
var pathInfo = fabric.util.getPathSegmentsInfo(textPath.path);
var pathLength = (pathInfo[pathInfo.length - 1].length / 10 / SIGN.scaleFac) * textPath.scaleX;
txt.pathLength += pathLength;
//console.log('Länge Ausschnitt (Zeile ' + i + '): ' + pathLength +' cm')
fontProp['Zeile' + i + '-LineProperties'] = 'LineHeight: ' + obj.getHeightOfLine(i) +', FontLineHeight' + txtObj['height'];
fontProp['Zeile' + i + '-PathCoords'] = 'WIDTH/HEIGHT: ' + textPath.width + ', ' + textPath.height + ', TOP/LEFT: ' + textPath.top + ', ' +textPath.left;
fontProp['Zeile' + i + '-PathLength'] = 'Länge Ausschnitt: ' + pathLength + ' cm';
});
/* CORRECT POSITION FOR EACH LINE */
//console.log('MinLeftOffset:' + txt.minLeftOffset)
layer.forEach(function(svgText,i)
{
//console.log(svgText);
switch(obj.textAlign)
{
//case 'left': txt.leftPos = obj.left + (txt.minLeftOffset * obj.scaleX); svgText.set({'left': txt.leftPos }); break;
case 'left': txt.leftPos = obj.left + (txt.minLeftOffset); svgText.set({'left': txt.leftPos }); break;
//case 'center': txt.leftPos = obj.left + txt.leftOffset; break; // no need, is already centered
//case 'right': txt.leftPos = (obj.left + obj.width) - (((txt.minLeftOffset * 2) * obj.scaleX) + svgText.width); svgText.set({'left': txt.leftPos }); break;
case 'right': txt.leftPos = (obj.left + obj.width) - svgText.width - txt.minLeftOffset; svgText.set({'left': txt.leftPos }); break;
}
//svgText.set({'left': txt.leftPos })
svgText.setCoords();
});
/* GROUP LAYERS AND PLACE EM */
var group = new fabric.Group(layer, {
left: obj.left,
top: obj.top,
selectable: true,
opacity:1,
evented: true,
scaleX: cScale,
scaleY: cScale,
//lockScalingX: true,
//lockScalingY: true
lockScalingFlip: true,
});
extendObject(group, 'mmkLayerType', 'layerVectorResult');
extendObject(group, 'mmkLayerUniqueID', obj.mmkLayerUniqueID);
extendObject(group, 'mmkLayerFill', obj.mmkLayerFill);
if(obj.mmkRenderAsCutForm) { extendObject(group, 'mmkRenderAsCutForm', true); }
if(obj.mmkSerienText) { extendObject(group, 'mmkSerienText', true); }
formatObjControls(group,1);
canvas.add(group);
canvas.setActiveObject(group);
/** RESET FONT EDITOR SCALE */
obj.set({'scaleX':cScale, 'scaleY': cScale, 'dirty': true}); // ensure scaleX,scaleY to be cScale
obj.set({'opacity' : SIGN.fontVectorizeOpacity, 'selectable': false, 'evented': false });
obj.setCoords();
fabric.util.clearFabricFontCache();
/** HIDE EDITOR FIELD AND MAKE AND DISABLE */
//console.log('FontProperties: ',fontProp);
//console.log('GroupSX: ' + group.scaleX + ', ObjSX: ' + obj.scaleX)
if(source=='obj_modified_addText') { group.viewportCenter(); }
group.setCoords();
canvas.renderAll; //.bind(canvas);
}
});
//console.log('Vectorization done...');
} // END OBJ_MODIFIED
}
async function saveTempSVG()
{
$('.svgDownWinContent').hide();
$('.loader2').show();
svgDownWin.open();
svgDownWin.disable();
var now = Date.now();
var tmpURL = $('.tmpDownloadButton').attr('href').split('?');
var newURL = tmpURL[0] + '?' +now;
$('.tmpDownloadButton').attr('href', newURL);
await calculateSign('saveTempSVG',1).then(value =>
{
//console.log('saveTempSVG calculateSign fertig');
var jsondata = JSON.stringify(canvas);
var svgdata = saveImageAs('svg');
$.ajax({type: "POST", url: "https://schilderstyle.de/konfigurator/scripts/mmk-io.php", cache: false, data: { com: 'saveTempSVG', svgdata: svgdata[0], filelist: svgdata[1], imgscale: svgdata[2] }}).done(function(cp)
{
svgDownWin.enable();
$('.loader2').hide();
$('.svgDownWinContent').show();
canvas.clear();
changeMaterialJS($('#MATERIALID').val(),$('#PRODUCTID').val(),jsondata);
$('#schild').css('visibility','visible'); // better display
return true;
});
});
return false;
}
// * WRITE IMAGE DATA *//
function saveImageAs(format)
{
var dataURL='';
$('#schild').css('visibility','hidden'); // better display
// DESELECT ALL OBJECTS
//canvas.deactivateAll().renderAll(); // NOT WORKING IN 2.x
canvas.discardActiveObject();
var addID = new Array();
var removeID=new Array();
switch(format)
{
case 'png':
/* FIX ZOOM */
//var baseTransform = canvas.viewportTransform;
//canvas.viewportTransform = fabric.IMatrix.slice(0);
//dataURL = canvas.toDataURL('image/png'); // PNG OUTPUT
//canvas.viewportTransform = baseTransform;
var viewport = canvas.viewportTransform;
canvas.viewportTransform = [1, 0, 0, 1, 0, 0];
dataURL = canvas.toDataURL('image/png'); //{format: 'jpeg',quality: 0.3, multiplier: 0.2});
// bounce here
canvas.viewportTransform = viewport;
//canvas.toDataURL(...options);
//dataURL = buffer.toDataURL('image/png'); // PNG OUTPUT
//var ctx = canvas.getContext("2d");
//var myImageData = ctx.getImageData(canvas.item(0).getLeft(), canvas.item(0).getTop(), canvas.item(0).get('width'), canvas.item(0).get('height'));
// buffer = document.createElement('canvas');
//var bufferCtx = buffer.getContext("2d");
// buffer.width = canvas.item(0).get('width');
// buffer.height = canvas.item(0).get('height');
// bufferCtx.putImageData(myImageData, 0, 0);
break;
case 'json':
dataURL = canvas.toJSON();
break;
case 'svg':
// GROUPS
//var engraveGroup = new Array();
//var cutGroup = new Array();
var imageScale = new Array();
var imageGroup = new Array();
var w,imgScaleFac,i,items,groupX,groupY;
// XY CORRECT
var objX= canvas.item(0).get('left');
var objY= canvas.item(0).get('top');
// FORMAT OBJECTS TO CSVG
LOG && console.log('Create SVG WorkingFile:');
LOG && console.log('------------------------------------------------------------------');
for(x=0; x canvas.item(x).get('height'))
// {
//xcorrect=0;
//ycorrect= $('#HEIGHT').val() - dy;
// ty = $('#HEIGHT').val() - ty;
// dy = $('#HEIGHT').val() - dy;
// }
// else
// {
//xcorrect= $('#WIDTH').val() - dx;
//ycorrect= 0;
// tx = $('#WIDTH').val() - tx;
// dx = $('#WIDTH').val() - dx;
// }
// console.log('XCORR: '+ canvas.item(x).get('scaleX') +'/'+ sx +', YCORR: '+ canvas.item(x).get('scaleY') + '/' + sy);
// BORDER STUFF HERE
//if(x==1)
//{
// console.log('BORDERID: ' + $('#BORDERID').val());
// alert('hold it');
//}
if(x==1)
{
switch($('#BORDERID').val())
{
//case '2': dx=dx - 2; dy = dy - 2; break; //Thin (2mm vom Rand)
//case '3': dx=dx - 5; dy = dy - 5; break; //Thick (5mm vom Rand)
}
//console.log('Layer: ' + x+' Type: '+type+', '+'tx|ty: ' +tx+','+ty+ ' dx|dy: ' +dx+ ',' +dy+ ' sx|sy: ' +sx+ ',' +sy+ ' width/height: ' + obj.get('width')+',' + obj.get('height')+ ' scaleFac: '+SIGN.scaleFac + ' sdx|sdy: ' +sdx+ ',' +sdy);
//console.log('DIM: ' +dx+ ',' +dy+ ',' +tx+ ',' +ty);
//alert('hold it');
}
switch(type)
{
case 'rect' : obj.set({ width: dx,
height: dy,
left: tx,
top: ty,
});
if($('#FORMDATA').val()=='rounded' && x==0)
{
obj.set({ rx: SIGN.cornerRadius, // * SIGN.scaleFac,
ry: SIGN.cornerRadius, // * SIGN.scaleFac,
});
}
break;
case 'ellipse': obj.set({ top: ty,
left: tx,
rx: canvas.item(x).getRx()/SIGN.scaleFac,
ry: canvas.item(x).getRy()/SIGN.scaleFac,
//scaleX: sx/2,
//scaleY: sy/2,
});
break;
case 'circle' : obj.set({ left: tx,
top: ty,
scaleX: sx,
scaleY: sy,
});
break;
case 'image' : w = canvas.item(x).get('width') * canvas.item(x).get('scaleX') / SIGN.scaleFac;
h = canvas.item(x).get('height') * canvas.item(x).get('scaleY') / SIGN.scaleFac;
imgScaleFacX = w/canvas.item(x).get('width');
imgScaleFacY = h/canvas.item(x).get('height');
obj.set({ top: ty,
left: tx,
scaleX: 1,
scaleY: 1,
});
// push original file name + imgScaleFac to array();
//imageScale = imageScale + "" + imgScaleFac +'|';
imageScale.push(imgScaleFacX);
imageScale.push(imgScaleFacY);
imageGroup.push(obj.getSrc());
break;
case 'polygon':
case 'triangle':
case 'path' :
case 'path-group':
case 'group' :
if(obj.mmkLayerType=='layerComponent')
{
/** HAS 2 Objects Fixation + Overlay **/
i=0;
items = obj._objects;
var groupX = obj.get('left');
var groupY = obj.get('top');
var groupScaleX = obj.get('scaleX');
var groupScaleY = obj.get('scaleY');
var groupWidth = obj.get('width');
var groupHeight = obj.get('height');
removeID.push(x);
while (i < items.length)
{
LOG && console.log('I: ' + i + ', GROUP Left/Top: ' + obj.left + ',' + obj.top + ', Item Left/Top: ' + items[i].left + ',' + items[i].top + ', Group Width/Height ' + obj.width +',' + obj.height + ', ScaleX/ScaleY ' + obj.scaleX +',' + obj.scaleY +', LAYERDATA: ' + items[i].mmkLayerType + ', OBJECTID: ' + items[i].mmkObjectID);
LOG && console.log('WIDTH/HEIGHT: ' + canvas.width + ', ' + canvas.height);
varx = obj._objects[i].get('left') * groupScaleX + groupX + (groupWidth/2) * groupScaleX;
vary = obj._objects[i].get('top') * groupScaleY + groupY + (groupHeight/2) * groupScaleY;
if(i==0)
{
items[i].set({left: varx, top: vary, scaleX: groupScaleX, scaleY: groupScaleY, fill:'', selectable : true, mmkLayerType: 'layerCompFixation' });
canvas.add(items[i]); canvas.renderAll();
}
i++;
}
}
else
{
obj.set({ top: ty,
left: tx,
scaleX: sx,
scaleY: sy,
});
}
break;
case 'i-text':
if(obj.mmkLayerType=='layerVectorEditor')
{
removeID.push(x); // not needed in SVG
}
else
{
obj.set({'top': ty, 'left': tx, 'scaleX': sx, 'scaleY': sy, });
}
break;
}
// BG LAYER
if(x==0 || obj.mmkLayerType=='layerCutForm' || obj.mmkLayerType=='layerFixation' || obj.mmkLayerType=='layerCompFixation')
{
if(x==0) { obj.set({ shadow:'none' }); }
if(obj.mmkLayerType=='layerCutForm')
{
/** CORRECT POSITION CAUSED BY STROKE */
obj.set({'left': obj.get('left') + (SIGN.cutFormStrokeWidth/2/SIGN.scaleFac),
'top': obj.get('top') + (SIGN.cutFormStrokeWidth/2/SIGN.scaleFac),
});
}
obj.set({strokeWidth: 0.001, stroke: '#ff0000', fill:'', strokeDashArray: []}); //, shadow: 'none'
}
else if(obj.mmkRenderAsCutForm && obj.type=='group')
{
/** CORRECT FOR COREL // POSITION CAUSED BY STROKE */
var group = obj;
//console.log(group);
for (var i=0; i < group.getObjects().length; i++)
{
group.item(i).set({'left': group.item(i).left + (SIGN.cutFormStrokeWidth/2/SIGN.scaleFac),
'top': group.item(i).top + (SIGN.cutFormStrokeWidth/2/SIGN.scaleFac),
'strokeWidth': 0.001, 'stroke': '#ff0000', 'fill':'', 'strokeDashArray': []
});
}
}
else if(obj.mmkLayerType=='layerOverlay')
{
removeID.push(x);
}
else
{
if(obj.mmkLayerFill && obj.mmkLayerFill==1) // layerFillColor
{
//ist ein LayerFill auf dem Obj. -> tue nichts
}
else
{
if(obj.get('type')=='image')
{
if($('#ENGRAVEMETHOD option:selected').val()!=8)
{
obj.filters.push(filterBlendColor('#000000'));
obj.applyFilters();
canvas.renderAll;
}
}
else
{
fillObjWithColor(obj, 'rgba(0,0,0,1)');
}
}
}
// obj.setCoords();
//canvas.renderAll();
}
// REMOVE BORDER LAYER IF NOT PRESENT
if($('#BORDERID').val()>1 && $('#BORDERID').val()<4)
{
var bw = canvas.item(1).get('width');
var bh = canvas.item(1).get('height');
var bwt = 0;
switch($('#BORDERID').val())
{
case '2': bwt=2; break; //Thin
case '3': bwt=5; break; //Thick
}
//var bwt = 5; //parseInt(5 * SIGN.scaleFac);
canvas.item(1).set({ strokeWidth: bwt, stroke: '#000000', fill:'rgba(255,255,255,0)'});
if($('#FORMDATA').val()=='rounded')
{
canvas.item(1).set({ rx: SIGN.cornerRadius, // * SIGN.scaleFac,
ry: SIGN.cornerRadius, // * SIGN.scaleFac,
});
}
}
else { //canvas.item(1).remove();
removeID.unshift(1);
}
obj.setCoords();
canvas.renderAll();
// REMOVE OVERLAYS // BORDER // GROUPS LAYERS ETC.
for(var x = removeID.length; x--;)
{
fx=removeID[x];
canvas.remove(canvas.item(fx));
}
/* REMOVE EXISTING OVERLAY IMAGES */
canvas.setOverlayImage(null,canvas.renderAll.bind(canvas));
// ADD COMPONENT FIXATIONS
// ADD ORIGINAL IMAGES
var fileList=''; var fileObj='';
for (index = 0; index < imageGroup.length; ++index)
{
fileList = fileList + imageGroup[index] +'\n';
file = imageGroup[index].replace('https://schilderstyle.de/konfigurator/xuser/uploads/','');
fileObj = fileObj + file +',';
}
if(fileList.length>0)
{
//var text = new fabric.Text('Originaldateien/URL\n' + fileList, { left: 0, top: -80, fontFamily: 'Arial', fontSize: 7 });
//canvas.add(text);
//obj.setCoords();
//canvas.renderAll();
}
obj.setCoords();
canvas.renderAll();
// WRITE SVG DATA
var dim= new Array();
if($('#DIMMODE0').is(':checked')) { dim = $('#DIMSTD').val().split('x'); }
if($('#DIMMODE1').is(':checked')) { dim = [$('#WIDTH').val(),$('#HEIGHT').val()]; }
dataURL = canvas.toSVG({suppressPreamble: 1, viewBox: { x: 0, y: 0, width: dim[0], height: dim[1]}});
//dataURL = canvas.toSVG();
//alert(dataURL);
//alert('Berechne...');
break;
}
return [dataURL,fileObj,imageScale.join('|')];
}
/** ---------------------------------------------------------------------------*/
/** CONVERT TEXT TO SVG */
/** ---------------------------------------------------------------------------*/
async function preloadFonts()
{
const fontList = { 'SST_BlackOpsOne' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Black Ops One/Black-Ops-One-Regular.ttf','SST_Bungee' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Bungee/Bungee-Regular.ttf','SST_CinzelDecorative' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Cinzel Decorative/Cinzel-Decorative-Regular.ttf', 'SST_CinzelDecorativeBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Cinzel Decorative/Cinzel-Decorative-Bold.ttf','SST_CourierPrime' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Courier Prime/Courier-Prime-Regular.ttf', 'SST_CourierPrimeItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Courier Prime/Courier-Prime-Italic.ttf', 'SST_CourierPrimeBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Courier Prime/Courier-Prime-Bold.ttf', 'SST_CourierPrimeBoldItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Courier Prime/Courier-Prime-BoldItalic.ttf','SST_DancingScript' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Dancing Script/Dancing-Script-Regular.ttf', 'SST_DancingScriptBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Dancing Script/Dancing-Script-Bold.ttf','SST_ElementalEnd' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Elemental End/Elemental-End-Regular.ttf', 'SST_ElementalEndItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Elemental End/Elemental-End-Italic.ttf','SST_LindenHill' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Linden Hill/Linden-Hill-Regular.ttf', 'SST_LindenHillItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Linden Hill/Linden-Hill-Italic.ttf','SST_Montserrat' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Montserrat/Montserrat-Regular.ttf', 'SST_MontserratItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Montserrat/Montserrat-Italic.ttf', 'SST_MontserratBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Montserrat/Montserrat-Bold.ttf', 'SST_MontserratBoldItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Montserrat/Montserrat-BoldItalic.ttf','SST_ProtestGuerrilla' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Protest Guerrilla/Protest-Guerrilla-Regular.ttf','SST_SairaStencilOne' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Saira Stencil One/Saira-Stencil-One-Regular.ttf','SST_Sansita' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Sansita/Sansita-Regular.ttf', 'SST_SansitaItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Sansita/Sansita-Italic.ttf', 'SST_SansitaBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Sansita/Sansita-Bold.ttf', 'SST_SansitaBoldItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Sansita/Sansita-BoldItalic.ttf','SST_Satisfy' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Satisfy/Satisfy-Regular.ttf','SST_SpaceMono' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Space Mono/Space-Mono-Regular.ttf', 'SST_SpaceMonoItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Space Mono/Space-Mono-Italic.ttf', 'SST_SpaceMonoBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Space Mono/Space-Mono-Bold.ttf', 'SST_SpaceMonoBoldItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Space Mono/Space-Mono-BoldItalic.ttf','SST_Stick' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Stick/Stick-Regular.ttf','SST_Tillana' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Tillana/Tillana-Regular.ttf', 'SST_TillanaBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Tillana/Tillana-Bold.ttf','SST_Ubuntu' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Ubuntu/Ubuntu-Regular.ttf', 'SST_UbuntuItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Ubuntu/Ubuntu-Italic.ttf', 'SST_UbuntuBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Ubuntu/Ubuntu-Bold.ttf', 'SST_UbuntuBoldItalic' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Ubuntu/Ubuntu-BoldItalic.ttf','SST_VollkornSC' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Vollkorn SC/Vollkorn-SC-Regular.ttf', 'SST_VollkornSCBold' : 'https://schilderstyle.de/konfigurator/xkonf/fonts/Vollkorn SC/Vollkorn-SC-Bold.ttf' }
/** 'SST_Montserrat': 'https://schilderstyle.de/konfigurator/xkonf/fonts/Montserrat/Montserrat-Regular.ttf',
'SST_MontserratItalic': 'https://schilderstyle.de/konfigurator/xkonf/fonts/Montserrat/Montserrat-Italic.ttf',
'SST_MontserratBold': 'https://schilderstyle.de/konfigurator/xkonf/fonts/Montserrat/Montserrat-Bold.ttf',
'SST_MontserratBoldItalic': 'https://schilderstyle.de/konfigurator/xkonf/fonts/Montserrat/Montserrat-BoldItalic.ttf',
*/
/** ITERATE THROUGH LAYERS */
for(x=0; x < canvas.getObjects().length; x++)
{
let font = canvas.item(x).get('fontFamily');
if(canvas.item(x).get('type')=='i-text' && fontList[font] !== undefined && SIGN.fonts[font] === undefined)
{
SIGN.fonts[font] = await opentype.load(fontList[font]);
}
}
}
function textToPath(fontFile,txt,text)
{
// get properties of fabric.js object
let [type, string, fontSize] = [
txt.type,
text,
txt.fontSize
];
let [left, top, height, width] = [
txt.left,
txt.top,
txt.height,
txt.width
];
const font = fontFile;
//console.log(font);
/**
* Get metrics and ratios from font
* to calculate absolute offset values according to font size
*/
let unitsPerEm = font.unitsPerEm;
let ratio = fontSize / unitsPerEm;
// font.descender is a negative value - hence Math.abs()
let [ascender, descender] = [font.ascender, Math.abs(font.descender)];
let ascenderAbs = Math.ceil(ascender * ratio);
let descenderAbs = Math.ceil(descender * ratio);
let lineHeight = (ascender + descender) * ratio;
/**
* calculate difference between font path bounding box and
* canvas bbox (including line height)
*/
let font2CanvasRatio = (1 / lineHeight) * height;
let baselineY = top + ascenderAbs * font2CanvasRatio;
// Create path object from font
path = font.getPath(string, left, baselineY, fontSize, { 'features': 'liga', 'hinting': false, 'fill' : 'yellow' });
//path = font.getPath(string, left, top, fontSize);
let pathData = path.toPathData();
//console.log(path);
//console.log('CONSOLE LOG:' + pathData);
return {'pathData' : pathData,
'ascender' : ascender,
'ascenderAbs' : ascenderAbs,
'descender' : descender,
'descenderAbs' : descenderAbs,
'left' : txt.left,
'top' : txt.top,
'height' : txt.height,
'width': txt.width,
'lineHeight' : lineHeight,
'baselineY' : baselineY,
'ratio' : ratio,
'unitsPerEm' : unitsPerEm,
'font2CanvasRatio' : font2CanvasRatio} ;
}
/** ---------------------------------------------------------------------------*/
/** IMAGE /FILE UPLOADS */
/** ---------------------------------------------------------------------------*/
function uploadImage(file)
{
//$("#uploadResult").show();
var resultError=new Array();
var errorMessage = '';
$('.loader2').show();
$('.loaderError').hide();
uploadWin.disable();
xhr = new XMLHttpRequest();
xhr.open('post', 'https://schilderstyle.de/konfigurator/scripts/mmk-image.php', true);
xhr.onload = function() { LOG && console.log('Upload erfolgreich beendet!'); }
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
//delay(function() {
if(xhr.status == 200 && xhr.responseText.length > 0)
{
addImage(xhr.responseText); //$("#uploadResult").hide();
uploadWin.enable();
uploadWin.close();
}
else
{
if(xhr.responseText.length > 0) { resultError = xhr.responseText.split('|'); }
if(resultError[0]) { errorMessage= 'File/Reason: ' + resultError[0] + '
'; }
if(resultError[1]) { errorMessage= errorMessage + 'Error: ' + resultError[1] + ''; }
uploadWin.enable();
$('.loaderError').show();
$('.loader2').hide();
$('.loaderError').html('Es ist ein Fehler bei der Übertragung aufgetreten:
' + errorMessage + '
'); //xhr.abort();
}
//}, 3000);
}
}
var formData = new FormData();
formData.append('file', file);
xhr.send(formData);
}
function uploadXLS(file)
{
$('#xlsUploadResult').show();
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://schilderstyle.de/konfigurator/scripts/mmk-io.php', true);
xhr.onload = function() { LOG && console.log('Upload erfolgreich beendet!'); }
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if(xhr.responseText.length>0) { refreshSerienTextForm(xhr.responseText); $('#xlsUploadResult').hide(); }
//return xhr.responseText;
}
}
var formData = new FormData();
formData.append('file', file);
formData.append('com', 'loadXLS');
xhr.send(formData);
}
function uploadImageCutForm(file)
{
//$("#uploadResultCutForm").show();
var resultError=new Array();
var errorMessage = '';
$('.loader2').show();
$('.loaderError').hide();
uploadWin.disable();
xhr = new XMLHttpRequest();
xhr.open('post', 'https://schilderstyle.de/konfigurator/scripts/mmk-image.php', true);
xhr.onload = function() { LOG && console.log('Upload erfolgreich beendet!'); };
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
//delay(function() {
if(xhr.status == 200 && xhr.responseText.length > 0)
{
addImageCutForm(xhr.responseText); //$("#uploadResultCutForm").hide();
uploadWin.enable();
uploadWin.close();
}
else
{
if(xhr.responseText.length > 0)
{
resultError = xhr.responseText.split('|');
}
if(resultError[0]) { errorMessage= 'File/Reason: ' + resultError[0] + '
'; }
if(resultError[1]) { errorMessage= errorMessage + 'Error: ' + resultError[1] + ''; }
uploadWin.enable();
$('.loaderError').show();
$('.loader2').hide();
$('.loaderError').html('Es ist ein Fehler bei der Übertragung aufgetreten:
' + errorMessage + '
'); //xhr.abort();
}
//}, 3000);
}
}
var formData = new FormData();
formData.append('file', file);
xhr.send(formData);
}
function handleInputs(mode)
{
SIGN.blockClickEvents = mode == 'disable' ? true : false;
}
/** ---------------------------------------------------------------------------*/
/** VALIDATION AND HELPERS */
/** ---------------------------------------------------------------------------*/
function onlyDigits(evt)
{
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
function checkSignWidthHeight(width,height)
{
//var rex = new RegExp(/^\d{2,6}(\.\d{0,1})?$/);
var rex2 = new RegExp(/^\d{2,6}?$/);
width = filterObjectInput(width);
height = filterObjectInput(height);
//if(width.match(rex) && height.match(rex))
if(width.match(rex2) && height.match(rex2))
{
//if(width.match(rex2)) { $('#WIDTH').val(width+'.0'); } else { $('#WIDTH').val(width); }
//if(height.match(rex2)) { $('#HEIGHT').val(height+'.0'); } else { $('#HEIGHT').val(height); }
return true;
}
else
{ return false;}
}
function checkObjectWidthHeight(width,height)
{
width = filterObjectInput(width);
height = filterObjectInput(height);
var rex = new RegExp(/^\d{1,5}(\.\d{0,1})?$/);
var rex2 = new RegExp(/^\d{1,5}?$/);
if(width.match(rex) && height.match(rex))
{
if(width.match(rex2)) { $('#objWidth').val(width+'.0'); } else { $('#objWidth').val(width); }
if(height.match(rex2)) { $('#objHeight').val(height+'.0'); } else { $('#objHeight').val(height); }
if(height <= parseFloat($('#ENGRAVEMINFONTSIZE').val()))
{
// $('#errorbar').html('Die Mindestgravurh\u00F6he f\u00FCr diese Gravurmethode liegt bei '+$('#ENGRAVEMINFONTSIZE').val()+'mm!');
// $('#errorbar').show();
}
return true;
}
else
{ return false; }
}
function checkObjectMinimumHeight(obj)
{
if(obj.mmkLayerType=='layerVectorResult')
{
var sibling = getVectorResultSibling(obj,'layerVectorEditor');
if(sibling!=0) { canvas.item(sibling).set({'left': obj.left, 'top': obj.top, 'scaleX': obj.scaleX, 'scaleY': obj.scaleY}); }
if(obj.mmkRenderAsCutForm && obj.type=='group')
{
/** AUTO CORRECT TO MIN HEIGHT SIZE IF */
var lines = canvas.item(sibling).textLines.length;
//console.log('Zeilen: ' + lines);
//console.log(canvas.item(sibling));
var staerke = $('#STAERKE option:selected').text()
staerke = staerke.replace("mm",'');
staerke = parseFloat(staerke.replace(",",'.')).toFixed(2);
//console.log('Stärke: ' + staerke);
var lineHeight = parseFloat((obj.height/lines) * obj.scaleY / SIGN.scaleFac);
//console.log('Zeilenhöhe: ' + lineHeight +' mm');
var minLineHeight = [0,25,40,60];
var minHeightError = 0;
if(staerke < 2) { if(minLineHeight[1] > lineHeight) { minHeightError=1; }}
else if (staerke < 3) { if(minLineHeight[2] > lineHeight) { minHeightError=2; }}
else if (staerke >= 3) { if(minLineHeight[3] > lineHeight) { minHeightError=3; }}
if(minHeightError > 0)
{
var height = minLineHeight[minHeightError] * lines * SIGN.scaleFac;
var ratio = height / obj.height;
obj.set({'scaleX': ratio, 'scaleY' :ratio}); // 'lockScalingX' :true, lockScalingY: true }); //$('#objHeight').val((minHeight[0] * lines) +'.0')
restoreCutFormBorder(obj);
canvas.renderAll();
$('#objHeight, #textCutSize').val((minLineHeight[minHeightError] * lines) +'.0');
return 1;
}
}
}
return 0;
}
function checkQRCodeHeight(obj)
{
if(obj.mmkLayerType=='layerBarcode')
{
var minHeight = 20;
var objHeight = parseFloat((obj.height) * obj.scaleY / SIGN.scaleFac);
if(objHeight < minHeight)
{
var height = 20 * SIGN.scaleFac;
var ratio = height / obj.height;
obj.set({'scaleX': ratio, 'scaleY' :ratio});
//restoreCutFormBorder(obj);
canvas.renderAll();
$('#objHeight').val(height +'.0');
return 1;
}
}
return 0;
}
function checkObjectXY(x,y)
{
$('#errorbar').hide();
x = filterObjectInput(x);
y = filterObjectInput(y);
var rex = new RegExp(/^\d{1,5}(\.\d{0,1})?$/);
var rex2 = new RegExp(/^\d{1,5}?$/);
if(x.match(rex) && y.match(rex))
{
if(x.match(rex2)) { $('#objXPos').val(x+'.0'); } else { $('#objXPos').val(x); }
if(y.match(rex2)) { $('#objYPos').val(y+'.0'); } else { $('#objYPos').val(y); }
return true;
}
else
{ return false; }
}
function filterObjectInput(val)
{
val = val.replace(',','.');
val = val.replace(/\.$/, '');
val = val.replace(/^00+/, '');
return val;
}
function checkFixationInput(value,obj,mode)
{
value = filterObjectInput(value);
//value = value.replace(',','.'); //
//value = value.replace(/\.$/, ''); // remove solo point
//value = value.replace(/^0+/, ''); // remove leading zeroes
var rex = new RegExp(/^\d{1,5}(\.\d{0,2})?$/);
var rex1 = new RegExp(/^\d{1,5}(\.\d{0,1})?$/);
var rex2 = new RegExp(/^\d{1,5}?$/);
var inputCheckOk=0;
if(value.match(rex) || value.match(rex1) || value.match(rex2)) { inputCheckOk=1; }
switch(mode)
{
case 'diameter':
if(inputCheckOk==0) { $('#fixDiameter').val(SIGN.fixationDefaultDiameter); }
else { $(obj).val(value); }
break;
case 1:
if(inputCheckOk==0) { $('#fixVertikal1').val(SIGN.fixationDefaultDistance); }
else { $(obj).val(value); }
break;
case 2:
if(inputCheckOk==0) { $('#fixHorizontal2').val(SIGN.fixationDefaultDistance); }
else { $('#fixHorizontal2').val(value); }
break;
case 4:
if(inputCheckOk==0) { $(obj).val(SIGN.fixationDefaultDistance); }
else { $(obj).val(value); }
break;
}
}
function checkTextHeight(height)
{
//$('#errorbar').hide();
var rex = new RegExp(/^\d{1,5}(\.\d{0,1})?$/);
var rex2 = new RegExp(/^\d{1,5}?$/);
if(height.match(rex))
{
if(height.match(rex2)) { $('#textSize').val(height+'.0'); }
if(height <= parseFloat($('#ENGRAVEMINFONTSIZE').val()))
{
//$('#errorbar').html('Die Mindestschrifth\u00F6he f\u00FCr diese Gravurmethode liegt bei ' +$('#ENGRAVEMINFONTSIZE').val()+'mm!');
//$('#errorbar').show();
}
return true;
}
else
{ return false;}
}
function formBlurAll()
{
$("input").each(function() { $(this).blur(); });
$("textarea").each(function() { $(this).blur(); });
$("select").each(function() { $(this).blur(); });
}
function filterUCChars(text,oldtext) {
var rex = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff]|\u200D|\u2003)/g;
// CLEAN UP BACKSLASHES
//if(res=text.match(/\.{1}?/g))
//if(text.match(/\\.{1}/g))
//console.log(text);
//console.log(oldtext);
if(text.match(/[\n|\r|\t|\v|\f]/g) || text.match(/\\/g))
{
//res.forEach(function(e)
//{
//console.log(e);
//if(e.match(/[\n|\r|\t|\v|\f]/)) {}
//else
//{
//return oldtext; //}
//});
}
else
{ return text; }
if(text.match(rex))
{
//console.log('return oldtext');
//return text.replace(rex, '').trim(); //iText cannot remove
return oldtext;
}
else
{ //console.log('return text');
return text; }
}
function in_array(needle, haystack){
var found = 0;
for (var i=0, len=haystack.length;i