javascript - 通过 slider 更改字体大小

标签 javascript jquery

我们正在从 JSON 中获取文本并在页面中显示......

enter image description here

一旦用户点击文本,我们就会显示弹出框......

enter image description here

在弹出框中,我们显示 slider 更改文本字体大小here ....

问题:

但是在下面的代码片段中,字体大小没有改变......

这是代码笔:https://codepen.io/kidsdial/pen/vMpBrd

// Display pop up next to text
function closePopUp(el) {
    el.style.display = 'none';
    openID = null
}

function openPopUp(el) {
    ///console.log(" open is called ",id)
    if (openID != null) {
        closePopUp(openID)
    }
    el.style.display = 'block';
    openID = el;
}


let openID = null;


var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {  
   "layers":[  
      {  
         "x":0,
         "height":612,
         "layers":[  
            {  
               "x":160,
               "layers":[  
                  {  
                     "font":"Montserrat-Bold",
                     "x":66,
                     "y":93,
					 "width" : 801,
					 "height" : 371,
                     "type":"text",
					 "src" : "a7bde03063d9fc0ef14eecd18f7eba31_Font522.otf",
                     "size":60,
                     "text":"MAYER'S ANNUAL",
                     "name":"edit_mayer"
                  }
               ],
               "y":291,
               "name":"user_image_1"
            },
            {  
               "x":25,
               "layers":[  
                  {  
                     "font":"Montserrat-Bold",
                     "x":166,
                     "y":193,
					 "width" : 801,
					 "height" : 371,
					 "src" : "a7bde03063d9fc0ef14eecd18f7eba31_Font522.otf",
                     "type":"text",
                     "size":60,
                     "text":"SALE",
                     "name":"edit_sale"
                  }
               ],
               "y":22,
               "name":"L2"
            }
         ],
         "y":0,
         "width":612,
         "name":"L1"
      }
   ]
};

$(document).ready(function() {
   
    // Below code will fetch text from json file

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    height: layer.height,
                    width: layer.width,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        height,
                        width,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            height,
                            width,
                            name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data)

    {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);

        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        for (let {
                src,
                x,
                y,
                name
            } of arr) {
            $(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
            
            var mask = $(".container").mask({
                imageUrl: imageUrl,
                maskImageUrl: 'http://piccellsapp.com:1337/parse/files/PfAppId/' + src,
                onMaskImageCreate: function(img) {
                    // Mask image positions
                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                    // end

                },
                id: counter
            });
            table.push(mask);
            fileup.onchange = function() {

                let mask2 = table[target];
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";                    
            };
            counter++;
        }
        drawText(data);
    }
    json(jsonData);
}); // end of document ready

const fonts = []; // caching duplicate fonts

// Text code

function drawText(layer) {

    if (layer.type === 'image') return;

    if (!layer.type || layer.type === 'group') {
        return layer.layers.forEach(drawText)
    }

    if (layer.type === 'text') {
        const url = 'http://piccellsapp.com:1337/parse/files/PfAppId/' + layer.src;

        if (!fonts.includes(url)) {
            fonts.push(url);
            $("style").prepend("@font-face {\n" +
                "\tfont-family: \"" + layer.font + "\";\n" +
                "\tsrc: url(" + url + ") format('truetype');\n" +
                "}");
        }

        // Below is POP UP Code
        const lightId = 'light' + layer.name
        const lightIdString = '#' + lightId
        $('.container').append(
            '<a id ="' + layer.name + '" onclick="openPopUp(' + lightId + ')"' +
            '<div class="txtContainer" id = "text" contenteditable="true" ' +
            'style="' +
            'left: ' + layer.x + 'px; ' +
            'top: ' + layer.y + 'px; ' +
            'font-size: ' + layer.size + 'px; ' +
            '">' + layer.text + '</div></a>' +
            '<div id="light' + layer.name + '" class="white_content" style="' +
            'left: ' + layer.x + 'px; ' +
            'top: ' + layer.y + 'px; ' + '"> ' +
			$('#template2').html() + 
            '<a href="javascript:void(0)" onclick="closePopUp(' + lightId + ')">Close</a></div> <div>'
        );
        document.getElementById(lightId).style.left = layer.x + document.getElementById(layer.name).offsetWidth + 'px'
        // Above is POP UP Code
    }

}
// extempl code end	

// jq plugin 

(function($) {
    var JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
        }, options);


        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            div;
      

        container.updateStyle = function() {
            return new Promise((resolve, reject) => {
                context.beginPath();
                context.globalCompositeOperation = "source-over";
                image = new Image();
                image.setAttribute('crossOrigin', 'anonymous');
                image.src = settings.maskImageUrl;
                image.onload = function() {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    context.drawImage(image, 0, 0, image.width, image.height);
                    div.css({
                        "width": image.width,
                        "height": image.height
                    });
                    resolve();
                };
            });
        };

        function renderInnerImage() {
            img = new Image();
            img.setAttribute('crossOrigin', 'anonymous');
            img.src = settings.imageUrl;
            img.onload = function() {
                settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
                settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
                context.globalCompositeOperation = 'source-atop';
                context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
                initImage = false;
            };
        }

        // change the draggable image

        container.loadImage = function(imageUrl) {
            console.log("load");
            //if (img)
            // img.remove();
            // reset the code.
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;
            settings.imageUrl = imageUrl;
            initImage = true;
            container.updateStyle().then(renderInnerImage);
            // sirpepole  Add this
            return settings.id;
        };       
     };
}(jQuery));

// slider text

$('input').on('input', function () {
    var v = $(this).val();
    $(text).css('font-size', v + 'px')
});
.container {
	background: gold;
	position: relative;
}

.container img {
	position: absolute;
	top: 0;
	bottom: 250px;
	left: 0;
	right: 0;
	margin: auto;
	z-index: 999;
}

.txtContainer {
	position: absolute;
	text-align: center;
	color: #FFF
}

.txtContainer:hover {
	background: red;
	padding: 1px;
	border-style: dotted;
}

.pip {
	display: inline-block;
	margin: 0;
	position: absolute;
}

.white_content {
	display: none;
	position: absolute;
	top: 25%;
	left: 25%;
	width: 50%;
	height: 50%;
	padding: 16px;
	border: 16px solid orange;
	background-color: white;
	z-index: 1002;
	overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js">
</script>

<input id="fileup" name="fileup" type="file" style="display:none" >

<div class="container"></div>

<template id='template2'>
  <input type="range" min="10" max="40">
</template>

最佳答案

我只是更新了您的脚本并进行了一些修复,但您还必须更新您的代码结构。现在你的代码有点复杂和困惑。试试这个我希望它能帮助你。谢谢

// Display pop up next to text
function closePopUp(el) {
    el.style.display = 'none';
    openID = null
}

function openPopUp(el) {
    ///console.log(" open is called ",id)
    if (openID != null) {
        closePopUp(openID)
    }
    el.style.display = 'block';
    openID = el;
}

function fontRange(e) {
  var element = e.parentElement.id;
  element = "#edit_" + element.split("_")[1];
  $(element).css('font-size', e.value + 'px');
}

let openID = null;


var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {  
   "layers":[  
      {  
         "x":0,
         "height":612,
         "layers":[  
            {  
               "x":160,
               "layers":[  
                  {  
                     "font":"Montserrat-Bold",
                     "x":66,
                     "y":93,
					 "width" : 801,
					 "height" : 371,
                     "type":"text",
					 "src" : "a7bde03063d9fc0ef14eecd18f7eba31_Font522.otf",
                     "size":60,
                     "text":"MAYER'S ANNUAL",
                     "name":"edit_mayer"
                  }
               ],
               "y":291,
               "name":"user_image_1"
            },
            {  
               "x":25,
               "layers":[  
                  {  
                     "font":"Montserrat-Bold",
                     "x":166,
                     "y":193,
					 "width" : 801,
					 "height" : 371,
					 "src" : "a7bde03063d9fc0ef14eecd18f7eba31_Font522.otf",
                     "type":"text",
                     "size":60,
                     "text":"SALE",
                     "name":"edit_sale"
                  }
               ],
               "y":22,
               "name":"L2"
            }
         ],
         "y":0,
         "width":612,
         "name":"L1"
      }
   ]
};

$(document).ready(function() {
   
    // Below code will fetch text from json file

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    height: layer.height,
                    width: layer.width,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        height,
                        width,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            height,
                            width,
                            name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data)

    {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);

        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        for (let {
                src,
                x,
                y,
                name
            } of arr) {
            $(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
            
            var mask = $(".container").mask({
                imageUrl: imageUrl,
                maskImageUrl: 'http://piccellsapp.com:1337/parse/files/PfAppId/' + src,
                onMaskImageCreate: function(img) {
                    // Mask image positions
                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                    // end

                },
                id: counter
            });
            table.push(mask);
            fileup.onchange = function() {

                let mask2 = table[target];
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";                    
            };
            counter++;
        }
        drawText(data);
    }
    json(jsonData);
}); // end of document ready

const fonts = []; // caching duplicate fonts

// Text code

function drawText(layer) {

    if (layer.type === 'image') return;

    if (!layer.type || layer.type === 'group') {
        return layer.layers.forEach(drawText)
    }

    if (layer.type === 'text') {
        const url = 'http://piccellsapp.com:1337/parse/files/PfAppId/' + layer.src;

        if (!fonts.includes(url)) {
            fonts.push(url);
            $("style").prepend("@font-face {\n" +
                "\tfont-family: \"" + layer.font + "\";\n" +
                "\tsrc: url(" + url + ") format('truetype');\n" +
                "}");
        }

        // Below is POP UP Code
        const lightId = 'light' + layer.name
        const lightIdString = '#' + lightId
        $('.container').append(
            '<a id ="' + layer.name + '" onclick="openPopUp(' + lightId + ')"' +
            '<div class="txtContainer" id = "text" contenteditable="true" ' +
            'style="' +
            'left: ' + layer.x + 'px; ' +
            'top: ' + layer.y + 'px; ' +
            'font-size: ' + layer.size + 'px; ' +
            '">' + layer.text + '</div></a>' +
            '<div id="light' + layer.name + '" class="white_content" style="' +
            'left: ' + layer.x + 'px; ' +
            'top: ' + layer.y + 'px; ' + '"> ' +
			$('#template2').html() + 
            '<a href="javascript:void(0)" onclick="closePopUp(' + lightId + ')">Close</a></div> <div>'
        );
        document.getElementById(lightId).style.left = layer.x + document.getElementById(layer.name).offsetWidth + 'px'
        // Above is POP UP Code
    }

}
// extempl code end	

// jq plugin 

(function($) {
    var JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
        }, options);


        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            div;
      

        container.updateStyle = function() {
            return new Promise((resolve, reject) => {
                context.beginPath();
                context.globalCompositeOperation = "source-over";
                image = new Image();
                image.setAttribute('crossOrigin', 'anonymous');
                image.src = settings.maskImageUrl;
                image.onload = function() {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    context.drawImage(image, 0, 0, image.width, image.height);
                    div.css({
                        "width": image.width,
                        "height": image.height
                    });
                    resolve();
                };
            });
        };

        function renderInnerImage() {
            img = new Image();
            img.setAttribute('crossOrigin', 'anonymous');
            img.src = settings.imageUrl;
            img.onload = function() {
                settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
                settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
                context.globalCompositeOperation = 'source-atop';
                context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
                initImage = false;
            };
        }

        // change the draggable image

        container.loadImage = function(imageUrl) {
            console.log("load");
            //if (img)
            // img.remove();
            // reset the code.
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;
            settings.imageUrl = imageUrl;
            initImage = true;
            container.updateStyle().then(renderInnerImage);
            // sirpepole  Add this
            return settings.id;
        };       
     };
}(jQuery));

// slider text

$('input').on('input', function () {
    var v = $(this).val();
    $(text).css('font-size', v + 'px')
});
.container {
	background: gold;
	position: relative;
}

.container img {
	position: absolute;
	top: 0;
	bottom: 250px;
	left: 0;
	right: 0;
	margin: auto;
	z-index: 999;
}

.txtContainer {
	position: absolute;
	text-align: center;
	color: #FFF
}

.txtContainer:hover {
	background: red;
	padding: 1px;
	border-style: dotted;
}

.pip {
	display: inline-block;
	margin: 0;
	position: absolute;
}

.white_content {
	display: none;
	position: absolute;
	top: 25%;
	left: 25%;
	width: 50%;
	height: 50%;
	padding: 16px;
	border: 16px solid orange;
	background-color: white;
	z-index: 1002;
	overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js">
</script>

<input id="fileup" name="fileup" type="file" style="display:none" >

<div class="container"></div>

<template id='template2'>
  <input type="range" min="10" max="40" oninput="fontRange(this)" onchange="fontRange(this)">
</template>

关于javascript - 通过 slider 更改字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55705799/

相关文章:

javascript - 如何捕获键盘事件来自哪些键?

javascript - Bootstrap - 响应能力

jQuery 使用 .on ('click' 独立控制许多重复的 html 元素

javascript - 是否可以从 angularjs 中的 Controller 调用特定函数?

javascript - 使用 jQuery 更改 img 高度,使其与宽度具有一定的纵横比

javascript - 类型错误 : Cannot read property 'then' of undefined on webservice

javascript - 如何获取由 javascript html 编辑器控制的文本区域的值?

javascript - 需要使用 JQuery 附加到选择

jquery - 展开此代码以检查 head 中的 HTML 注释是否包含字符串

javascript - 将脚本绑定(bind)到单选按钮: Weird Behaviour : Not Binding by Name