无法在所有画布上上传图像

时间:2019-04-02 09:55:12

标签: javascript jquery html5 canvas image-uploading

我们允许用户在点击“透明图像” ...

时上传图像。

在下面的模板中,我们提供了一个选项,可以上传6张图片,效果很好:

enter image description here

下面是代码段1 在“整页模式”下查看代码段结果。...

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

let jsonData = {    
  "layers" : [
    {
      "x" : 0,
      "height" : 612,
      "layers" : [        
        {
          "x" : 20,
          "height" : 198,
          "layers" : [
            {
              "x" : 0,              
              "src" : "WLbCzRI.png",
              "y" : 0                            
            }            
          ],
          "y" : 294          
        },
        {
          "x" : 20,          
          "layers" : [
            {
              "x" : 0,
              
              "src" : "YmChyhu.png",
              "y" : 0              
            }
          ],
          "y" : 451          
        },
        {
          "x" : 294,          
          "layers" : [
            {
              "x" : 0,              
              "src" : "IeXKp5z.png",
              "y" : 0              
            }
            
          ],
          "y" : 390          
        },
        {
          "x" : 330,          
          "layers" : [
            {
              "x" : 0,              
              "src" : "I8shPlt.png",
              "y" : 0              
            }            
          ],
          "y" : 20          
        },
        {
          "x" : 20,
          "layers" : [
            {
              "x" : 0,              
              "src" : "h8MVKzd.png",
              "y" : 0
            }
          ],
          "y" : 124
        },
        {
          "x" : 20,
          "layers" : [
            {
              "x" : 0,              
              "src" : "J436UDQ.png",
              "y" : 0
            },            
          ],
          "y" : 20
        }
      ],
      "y" : 0
    }
  ]
};

$(document).ready(function() {

    // below code will upload image onclick mask image

    $('.container').click(function(e) {
        // filtering out non-canvas clicks
        if (e.target.tagName !== 'CANVAS') return;

        // getting absolute points relative to container
        const absX = e.offsetX + e.target.parentNode.offsetLeft + e.currentTarget.offsetLeft;
        const absY = e.offsetY + e.target.parentNode.offsetTop + e.currentTarget.offsetTop;

        const $canvasList = $(this).find('canvas');
        // moving all canvas parents on the same z-index
        $canvasList.parent().css({
            zIndex: 0
        });

        $canvasList.filter(function() { // filtering only applicable canvases
            const bbox = this.getBoundingClientRect()
            return (
                absX >= bbox.left && absX <= bbox.left + bbox.width &&
                absY >= bbox.top && absY <= bbox.top + bbox.height)
        }).each(function() { // checking white in a click position
            const x = absX - this.parentNode.offsetLeft - e.currentTarget.offsetLeft;
            const y = absY - this.parentNode.offsetTop - e.currentTarget.offsetTop;
            const pixel = this.getContext('2d').getImageData(x, y, 1, 1).data;
            if (pixel[3] === 255) {
                $(this).parent().css({
                    zIndex: 2
                })
                target = this.id;
                
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
            }
        })
    });

    // Below code will fetch mask images 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,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            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: 'https://i.imgur.com/' + src,
                onMaskImageCreate: function(img) {

                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });

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

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

// code to display image

(function($) {
    var JQmasks = [];
    $.fn.mask = function(options) {
      
        var settings = $.extend({          
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, 
            y: 0, 
            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.mousePosition = function(event) {
            return {
                x: event.pageX || event.offsetX,
                y: event.pageY || event.offsetY
            };
        }
		
		container.enable = function() {
            draggable = true;
            $(canvas).attr("active", "true");
            div.css({
                "z-index": 2
            });
        }

        container.disable = function() {
            draggable = false;
            $(canvas).attr("active", "false");
            div.css({
                "z-index": 1
            });
        }
		
        container.selected = function(ev) {
            var pos = container.mousePosition(ev);
            var item = $(".masked-img canvas").filter(function() {
                var offset = $(this).offset()
                var x = pos.x - offset.left;
                var y = pos.y - offset.top;
                var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
                return d[0] > 0
            });

            JQmasks.forEach(function(el) {
                var id = item.length > 0 ? $(item).attr("id") : "";
                if (el.id == id)
                    el.item.enable();
                else el.item.disable();
            });
        };
       
        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 draggable image

        container.loadImage = function(imageUrl) {                      
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;
            settings.imageUrl = imageUrl;
            initImage = true;
            container.updateStyle().then(renderInnerImage);
            // sir pepole code
            return settings.id;
			// sir pepole code end
        };


        // change  masked Image
        container.loadMaskImage = function(imageUrl, from) {
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            settings.maskImageUrl = imageUrl;
            div = $("<div/>", {
                "class": "masked-img"
            }).append(canvas);

            // div.find("canvas").on('touchstart mousedown', function(event)
            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);
            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
            container.loadImage(settings.imageUrl);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        })
        return container;
    };
}(jQuery));
.temp {}

.container {
	background: gold;
  position: relative;
 
}

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

.masked-img {
	overflow: hidden;	
	position: relative;
}

.remove {
  display: block;
  background: #444;
  border: 1px solid black;
  color: white;
  text-align: center;
  cursor: pointer;
}
.remove:hover {
  background: white;
  color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

<div class="container">

</div>

问题

然后,我们提供了一个选项,可以使用以下代码删除上传的图片。...

现在用户不能在所有透明图像[最后一个画布]上上传图像,如下面的代码片段所示。...

const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));

$("<br/><span id=\"" + newImageLoadedId + "\" class=\"remove\">Remove image</span>").insertAfter("#fileup");

$(".remove").click(function(event) {
    const canvasId = "canvas#" + event.currentTarget.id;
    // Delete the image
    const ctx = $("canvas")[event.currentTarget.id].getContext("2d");
    ctx.fillStyle = "white"
    ctx.fillRect(0, 0, 500, 500)
    // Delete the button
    $(this).remove();
});   

enter image description here

代码段2

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

let jsonData = {    
  "layers" : [
    {
      "x" : 0,
      "height" : 612,
      "layers" : [        
        {
          "x" : 20,
          "height" : 198,
          "layers" : [
            {
              "x" : 0,              
              "src" : "WLbCzRI.png",
              "y" : 0                            
            }            
          ],
          "y" : 294          
        },
        {
          "x" : 20,          
          "layers" : [
            {
              "x" : 0,
              
              "src" : "YmChyhu.png",
              "y" : 0              
            }
          ],
          "y" : 451          
        },
        {
          "x" : 294,          
          "layers" : [
            {
              "x" : 0,              
              "src" : "IeXKp5z.png",
              "y" : 0              
            }
            
          ],
          "y" : 390          
        },
        {
          "x" : 330,          
          "layers" : [
            {
              "x" : 0,              
              "src" : "I8shPlt.png",
              "y" : 0              
            }            
          ],
          "y" : 20          
        },
        {
          "x" : 20,
          "layers" : [
            {
              "x" : 0,              
              "src" : "h8MVKzd.png",
              "y" : 0
            }
          ],
          "y" : 124
        },
        {
          "x" : 20,
          "layers" : [
            {
              "x" : 0,              
              "src" : "J436UDQ.png",
              "y" : 0
            },            
          ],
          "y" : 20
        }
      ],
      "y" : 0
    }
  ]
};

$(document).ready(function() {

    // below code will upload image onclick mask image

    $('.container').click(function(e) {
        // filtering out non-canvas clicks
        if (e.target.tagName !== 'CANVAS') return;

        // getting absolute points relative to container
        const absX = e.offsetX + e.target.parentNode.offsetLeft + e.currentTarget.offsetLeft;
        const absY = e.offsetY + e.target.parentNode.offsetTop + e.currentTarget.offsetTop;

        const $canvasList = $(this).find('canvas');
        // moving all canvas parents on the same z-index
        $canvasList.parent().css({
            zIndex: 0
        });

        $canvasList.filter(function() { // filtering only applicable canvases
            const bbox = this.getBoundingClientRect()
            return (
                absX >= bbox.left && absX <= bbox.left + bbox.width &&
                absY >= bbox.top && absY <= bbox.top + bbox.height)
        }).each(function() { // checking white in a click position
            const x = absX - this.parentNode.offsetLeft - e.currentTarget.offsetLeft;
            const y = absY - this.parentNode.offsetTop - e.currentTarget.offsetTop;
            const pixel = this.getContext('2d').getImageData(x, y, 1, 1).data;
            if (pixel[3] === 255) {
                $(this).parent().css({
                    zIndex: 2
                })
                target = this.id;
                
                setTimeout(() => {
                    $('#fileup').click();
                }, 20);
            }
        })
    });

    // Below code will fetch mask images 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,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            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: 'https://i.imgur.com/' + src,
                onMaskImageCreate: function(img) {

                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });

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

                let mask2 = table[target];
                //  mask2.loadImage(URL.createObjectURL(fileup.files[0]));

                // code to Remove image
                const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                //	 code to Remove image end
                document.getElementById('fileup').value = "";

                // code to Remove image

                $("<br/><span id=\"" + newImageLoadedId + "\" class=\"remove\">Remove image</span>").insertAfter("#fileup");

                $(".remove").click(function(event) {
                    const canvasId = "canvas#" + event.currentTarget.id;
                    // Delete the image
                    const ctx = $("canvas")[event.currentTarget.id].getContext("2d");
                    ctx.fillStyle = "white"
                    ctx.fillRect(0, 0, 500, 500)
                    // Delete the button
                    $(this).remove();
                });

                //  code to remove image end here....	
            };
            counter++;
        }
       
    }
    json(jsonData);
}); // end of document ready

// code to display image

(function($) {
    var JQmasks = [];
    $.fn.mask = function(options) {
      
        var settings = $.extend({          
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, 
            y: 0, 
            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.mousePosition = function(event) {
            return {
                x: event.pageX || event.offsetX,
                y: event.pageY || event.offsetY
            };
        }
		
		container.enable = function() {
            draggable = true;
            $(canvas).attr("active", "true");
            div.css({
                "z-index": 2
            });
        }

        container.disable = function() {
            draggable = false;
            $(canvas).attr("active", "false");
            div.css({
                "z-index": 1
            });
        }
		
        container.selected = function(ev) {
            var pos = container.mousePosition(ev);
            var item = $(".masked-img canvas").filter(function() {
                var offset = $(this).offset()
                var x = pos.x - offset.left;
                var y = pos.y - offset.top;
                var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
                return d[0] > 0
            });

            JQmasks.forEach(function(el) {
                var id = item.length > 0 ? $(item).attr("id") : "";
                if (el.id == id)
                    el.item.enable();
                else el.item.disable();
            });
        };
       
        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 draggable image

        container.loadImage = function(imageUrl) {                      
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;
            settings.imageUrl = imageUrl;
            initImage = true;
            container.updateStyle().then(renderInnerImage);
            // sir pepole code
            return settings.id;
			// sir pepole code end
        };


        // change  masked Image
        container.loadMaskImage = function(imageUrl, from) {
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            settings.maskImageUrl = imageUrl;
            div = $("<div/>", {
                "class": "masked-img"
            }).append(canvas);

            // div.find("canvas").on('touchstart mousedown', function(event)
            div.find("canvas").on('dragstart', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.onDragStart(event);
            });

            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === false) return;
                event.handled = true;
                container.selected(event);
            });

            div.find("canvas").bind("dragover", container.onDragOver);
            container.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
            container.loadImage(settings.imageUrl);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        })
        return container;
    };
}(jQuery));
.temp {}

.container {
	background: gold;
  position: relative;
 
}

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

.masked-img {
	overflow: hidden;	
	position: relative;
}

.remove {
  display: block;
  background: #444;
  border: 1px solid black;
  color: white;
  text-align: center;
  cursor: pointer;
}
.remove:hover {
  background: white;
  color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

<div class="container">

</div>

修改

一旦我删除了This code,并且如果我使用了pastebin code,那么我就可以在所有画布上上传图片了。...因此删除图片代码与上述链接代码有冲突。...

0 个答案:

没有答案