我需要用来自计算机的文件上传中的新图像替换现有图像,我想用新上传的图像替换图像。 Here is the code (JSFiddle)
var canvas = new fabric.Canvas('c');
function addImage () {
fabric.Image.fromURL('http://lorempixel.com/400/200', function (img) {
img.set({ 'left': 50 });
img.set({ 'top': 50 });
img.scaleToWidth(100);
img.scaleToHeight(100);
canvas.add (img);
});
}
addImage();
canvas {
border:1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.2/fabric.min.js"></script>
<canvas id="c" width="400" height="200"></canvas>
<span><input type="file" name="" id="span"></span>
答案 0 :(得分:9)
你可以通过以下方式实现这一目标......
var canvas = new fabric.Canvas('c');
function addImage(imgLink) {
fabric.Image.fromURL(imgLink, function(img) {
img.set({ 'left': 50 });
img.set({ 'top': 50 });
img.scaleToWidth(100);
img.scaleToHeight(100);
var objs = canvas.getObjects();
if (objs.length) {
objs.forEach(function(e) {
if (e && e.type === 'image') {
e._element.src = imgLink;
canvas.renderAll();
}
});
} else canvas.add(img);
});
}
addImage('http://lorempixel.com/400/200');
// file upload
var span = document.querySelector('#span');
span.onchange = function(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function(file) {
addImage(file.target.result);
}
reader.readAsDataURL(file);
}
canvas {
border:1px solid lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.2/fabric.min.js"></script>
<canvas id="c" width="400" height="200"></canvas>
<span><input type="file" name="" id="span"></span>
答案 1 :(得分:0)
您可以使用以下代码
document.addEventListener('dblclick', function () {
if (canvas.getActiveObject().id == 'uimg0') {
$("input[id='span']").click();
$("#span").replaceWith($("#span").val('').clone(true));
}
});
var imgname = "http://lorempixel.com/400/200";
var pugImg0 = new Image();
var pug
pugImg0.onload = function (img) {
pug = new fabric.Image(pugImg0, {
left: 96,
top: 65,
scaleX: 508 / pugImg0.width,
scaleY: 208 / pugImg0.height,
id: 'uimg0',
selectable: true,
lockMovementX: true,
lockMovementY: true,
hasControls: false
});
canvas.add(pug);
};
pugImg0.src = imgname;
var imageLoader = document.getElementById('span');
imageLoader.addEventListener('change', handleImage0);
function handleImage0(e) {
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
var pugb;
img.onload = function () {
pugb = new fabric.Image(img, {
left: 78,
top: 103,
scaleX: 240 / img.width,
scaleY: 195 / img.height,
selectable: true,
id: "uimg0",
lockMovementX: true,
lockMovementY: true,
hasControls: false
})
canvas.add(pugb).renderAll();
}
img.src = event.target.result;
canvas.remove(canvas.getActiveObject());
}
reader.readAsDataURL(e.target.files[0]);
}