我的图像中有一个透明的框架。它被设置为CSS画布的背景。我能够将图像添加到画布中,但希望能够一次只添加一个图像到框架的透明部分后面。我怎么能做到这一点?提前谢谢!
var id = document.getElementById('rectangle') && rectangle ||
document.getElementById('anotherCanvas') && anotherCanvas;
var canvas = new fabric.Canvas(id);
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({
width: 125,
height: 170
})
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png',
quality: 1
});
});
};
reader.readAsDataURL(file);
});

canvas {
border: 1px solid #808080;
border-radius: 1px;
}
#rectangle {
background: url(http://i.imgur.com/0Mt6ho1.png);
background-size: contain;
background-repeat: no-repeat;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="rectangle" width="637" height="412"></canvas>
&#13;
答案 0 :(得分:1)
请添加到您的fabricjs图片对象左上方属性:
var oImg = img.set({
width: 125,
height: 170,
left: 430,
top: 65
})
要在上面制作上传图片,请不要使用背景图片。您应该插入没有控件的常规图像。像这样:
fabric.Image.fromURL('http://i.imgur.com/0Mt6ho1.png', function (img) {
var oImg = img.set({
scaleX: 0.2,
scaleY: 0.2,
selectable: false
})
canvas.add(oImg).renderAll();
});
然后,当您上传图片时,您需要选择它,后退并取消选择:
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({
width: 125,
height: 170,
left: 430,
top: 65
})
canvas.add(oImg);
canvas.setActiveObject(oImg);
var image = canvas.getActiveObject();
image.moveTo(-1);
canvas.discardActiveObject();
canvas.renderAll();
});
如果您将使用鼠标选择对象,它会自动将您的对象移动到顶部,但是当您取消选择时 - 它将再次移回。
选中此fiddle