应用场景:在做一个图形和文本及背景的设计器,然后用户通过导入Excel数据结合设计的模板来生成最终想要的图纸,打印出来以便给工人看,在公司大佬的建议下使用了FabricJS,但是在导入背景(底图)的过程中,自动生成的位置,客户总是不满意,所以干脆让他自己拖~~
获取用户上传的图片资源,用于保存显示
var objURL = null;
//获取安全模式下的图片真实路径(仅base64)
$(document).on('change', '#inputGroupFile02', function () {
//console.log(this.files[0]);
function getObjectURL(file) {
var url = null;
if (window.createObjcectURL != undefined) {
url = window.createOjcectURL(file);
} else if (window.URL != undefined) {
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) {
url = window.webkitURL.createObjectURL(file);
}
return url;
}
//返回input file的真实路径---base64
objURL = getObjectURL(this.files[0]);
});
// 读取图片地址,设置画布背景,objURL是用户上传的图片资源
fabric.Image.fromURL(objURL, (img) => {
var tscaleX = (canvas.height < canvas.width ? canvas.height : canvas.width) / (img.height < img.width ? img.height : img.width);
var tscaleY = (canvas.height < canvas.width ? canvas.height : canvas.width) / (img.height < img.width ? img.height : img.width);
if ((tscaleX * img.width) > canvas.width) {
var rscalex = canvas.width / img.width;
var imgscale = img.height / img.width;
var rscaley = ((rscalex * img.width) * imgscale)/img.height;
//再次缩放
tscaleX = rscalex;
tscaleY = rscaley;
}
img.set({
// 通过scale来设置图片大小,这里设置和画布一样大
scaleX: tscaleX,
scaleY: tscaleY
});
canvas.add(img.set({
// 通过scale来设置图片大小,这里设置和画布一样大
scaleX: tscaleX,
scaleY: tscaleY,
type: 'img'
}));
// 设置背景白色
canvas.setBackgroundColor("white");
// 设置背景,直接设置
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
canvas.renderAll();
});
发现一个神奇的现象,不知道为什么,直接设置背景之后还是可以拖动的,然后再删除target这个对象时,居然直接再拖动好的位置设置背景了,阴差阳错的实现了,记录一下~