用户单击“蒙版图像”后,我们允许用户上传自定义图像。...除了图像,我们还将显示文本“删除图像” ....
问题:
在单击该文本时,我想删除上载图片,例如codepen1。...但是现在,当我使用以下代码时,仅文本会被删除:
var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";
let jsonData = {
"layers" : [
{
"x" : 0,
"height" : 612,
"layers" : [
{
"x" : 0,
"y" : 0,
"name" : "L2a"
},
{
"x" : 160,
"layers" : [
{
"x" : 0,
"src" : "ax0HVTs.png",
"y" : 0,
"name" : "L2b-1"
},
{
"x" : 0,
"y" : 0,
"name" : "L2b-2"
}
],
"y" : 291,
"name" : "user_image_1"
},
{
"x" : 25,
"layers" : [
{
"x" : 0,
"src" : "hEM2kEP.png",
"y" : 0,
"name" : "L2C-1"
},
{
"x" : 0,
"y" : 0,
"name" : "L2C-2"
}
],
"y" :22,
"name" : "L2"
}
],
"y" : 0,
"width" : 612,
"name" : "L1"
}
]
};
$(document).ready(function() {
// below code will upload image onclick mask image
$('.container').click(function(e) {
var res = e.target;
target = res.id;
console.log(target);
if (e.target.getContext)
{
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');
if(name.indexOf('mask_') !== -1){
var imageUrl1 = imageUrl;
}else{
var imageUrl1 = '';
}
var mask = $(".container").mask({
imageUrl: imageUrl1,
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 = "";
// Below code to Remove image
$("<span class=\"pip\">" +
"<img src='https://i.imgur.com/' + src />" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#fileup");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
// Remove image code ended here....
};
counter++;
// get the text
}
}
json(jsonData);
}); // end of document ready
// 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.mousePosition = function(event) {
return {
x: event.pageX || event.offsetX,
y: event.pageY || event.offsetY
};
}
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.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.onDragStart = function(evt) {
if (evt.target.getContext) {
var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
$(canvas).attr("active", "true");
container.selected(evt);
prevX = evt.clientX;
prevY = evt.clientY;
var img = new Image();
evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
evt.originalEvent.dataTransfer.setData('text/plain', 'anything');
}
};
container.getImagePosition = function() {
return {
x: settings.x,
y: settings.y,
scale: settings.scale
};
};
container.onDragOver = function(evt) {
if (evt.target.getContext) {
var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
if (pixel[3] === 255) {
if (draggable && $(canvas).attr("active") === "true") {
var x = settings.x + evt.clientX - prevX;
var y = settings.y + evt.clientY - prevY;
if (x == settings.x && y == settings.y)
return; // position has not changed
settings.x += evt.clientX - prevX;
settings.y += evt.clientY - prevY;
prevX = evt.clientX;
prevY = evt.clientY;
clearTimeout(timeout);
timeout = setTimeout(function() {
container.updateStyle();
renderInnerImage();
}, 20);
}
} else {
evt.stopPropagation();
return false;
}
}
};
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);
};
// change the 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;
}
.txtContainer{ position:absolute; text-align:center; color:#FFF}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.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://code.jquery.com/jquery-3.3.1.min.js"></script>
<input id="fileup" name="fileup" type="file" style="display:none" >
<div class="container">
</div>
如果您需要其他任何信息,请告诉我。...
答案 0 :(得分:5)
因此,您首先应该解决2个不同的问题:
1)在按钮中如何引用您的图片。
按钮不是很聪明,您将需要添加一些魔术。就像您按照代码进行操作一样,基本上在加载图像时,您是在使用新绘制上载画布,因此识别要删除的内容并不容易。这种方法的一个问题是您很难找到要删除的图像。但是,一旦加载了图像,您可以在画布中返回有关此图像的信息,然后将其添加到数组中。
据我所知,每个画布只有一张图像,或者至少它将覆盖最后一张,因此最简单的解决方案是清洁整个画布。首先,我们返回包含图像的画布的ID:
// 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);
// Add this
return settings.id;
};
然后您可以将其保存在以下行中:const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
此挑战的第二步是将其基本添加为按钮的id(虽然这不是推荐的方法,但是会使您修改代码的方式减少):
$("<br/><span id=\"" + newImageLoadedId + "\" class=\"remove\">Remove image</span>").insertAfter("#fileup");
现在您的按钮具有对您上传的图像的引用。
2)实际上已将其删除。
这个问题比较容易,您只需要清除画布中的图像即可。
$(“ canvas#” + id).getContext('2d')。clearReact(...)
这就是全部,我建议您重构并清理一下代码。您可以添加一些改进,例如。
如果您要将一个以上的图像上传到画布,则此方法不是删除唯一图像的最佳方法,但是您的代码也不允许您立即正确执行此操作。如果要保留几张图像,建议您选中this answer,因此基本上,您需要将每个图像作为新图层进行跟踪。
使用closure处理click事件,而不是将ID保存到按钮中(这会使ID不是唯一的,而是存在于按钮和画布中)。 甚至例如使用计数器而不是时间戳,也可以使加载映像过程更加直观。
免责声明:此解决方案不能改善您的代码库,它只是为您遇到的问题提供了一种可能的解决方案,而建议的解决方案只涉及了尽可能少的行数。最后我建议的内容很少,但是随着时间的流逝以及对jQuery / JavaScript的更多了解,您将以更好的方式解决此问题。