问题遇到的现象和发生背景
fabric.js 填充图片使用toDataURL 导出base64格式的图片并放大图片,并且让填充的不裁剪
问题相关代码,请勿粘贴截图
<template>
<div>
<div style="margin: 0 auto">
<canvas
id="canvas"
width="600"
height="600"
style="width: 600px; height: 600px; border: 1px solid #333"
></canvas>
</div>
<el-button @click="addImg">添加图片</el-button>
<el-button @click="exportImg">导出图片</el-button>
</div>
</template>
<script>
export default {
// 组件名称
name: "",
// 组件参数 接收来自父组件的数据
props: {},
// 局部注册的组件
components: {},
// 组件状态值
data() {
return {
cvs: null,
};
},
// 计算属性
computed: {},
// 侦听器
watch: {},
// 组件方法
methods: {
addImg() {
var that = this;
const imG = new Image();
imG.crossOrigin = "Anonymous";
imG.src =
"https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2020%2F0515%2Fbfedfd18j00qadpg00014c000hs00b4c.jpg&thumbnail=660x2147483647&quality=80&type=jpg";
fabric.Image.fromURL(
imG.src,
(img) => {
that.cvs.add(
img.set({
scaleX: 1,
scaleY: 1,
})
);
that.cvs.renderAll();
that.cvs.fire("object:modified", {
target: img,
});
},
{ crossOrigin: "anonymous" }
);
},
exportImg() {
// var tempScaleX = this.cvs.getActiveObject().scaleX * 1;
// var tempScaleY = this.cvs.getActiveObject().scaleY * 1;
// this.cvs.getActiveObject().scaleX = tempScaleX;
// this.cvs.getActiveObject().scaleY = tempScaleY;
// this.cvs.renderAll();
// this.cvs.calcOffset();
let url = this.cvs.toDataURL({
width: 300,
height: 300,
multiplier: 3,
});
this.cvs.requestRenderAll();
console.log(url);
},
},
// 以下是生命周期钩子 注:没用到的钩子请自行删除
/**
* 组件实例创建完成,属性已绑定,但DOM还未生成,$ el属性还不存在
*/
created() {},
async mounted() {
this.cvs = new fabric.Canvas("canvas", {
preserveObjectStacking: true,
width: 600,
height: 600,
});
// 控件
fabric.Object.prototype.set({
hasControls: true, // 是否开启图层的控件
borderColor: "red", // 图层控件边框的颜色
cornerColor: "red", //激活状态角落图标的填充颜色
cornerStrokeColor: "red", //激活状态角落图标的边框颜色
cornerSize: 6, //控制点大小
transparentCorners: false, //激活状态角落的图标是否透明
});
},
};
</script>
<style scoped lang="less">
/deep/ .canvas-container {
margin: 50px auto;
}
</style>
运行结果及报错内容
在浏览器的效果
导出base64 图片发生了裁剪