注:图片是本地的图片,因为我用接口返回的图片地址的图片会有跨域问题,只好把要合成的图片放assets里
new URL(
../../../../assets/images/xxx.png
,
import.meta.url
).href;是拿到本地的图片,因为vite不能用import语法,只能使用这个语法 new URL(
../../../../assets/images/xxx
,
import.meta.url ).href;
canvas.toDataURL();是将画布转为base64图片
//两张图片融合合成图片
let canvas = document.createElement('canvas');
// 设置画布宽高
canvas.width = 600;
canvas.height = 379;
// canvas.width=this.divPosition.width
// canvas.height=this.divPosition.height
let ctx = canvas.getContext('2d');
// 然后加载第一张图片到Canvas中:
let img1 = new Image();
img1.src = new URL(
`../../../../assets/images/xxx.png`,
import.meta.url
).href; // 设置第一张图片路径
let img3 = new Image();
img3.src = new URL(
`../../../../assets/images/allMaterial/${articleType}.png`,
import.meta.url
).href; // 设置第一张图片路径
console.log('img1', img1.width, img1.height);
console.log('img2', img3.width, img3.height);
img1.onload = function () {
ctx.drawImage(img1, 0, 0, canvas.width, canvas.height); // 将第一张图片绘制到Canvas中,并设置宽高
};
// 接下来加载第二张图片到Canvas中:
//1. let img2 = document.getElementById("dragImg_"+ this.moveImg.id)
// 2.
let img2 = new Image();
// img2.crossOrigin="Anonymous"
//3. let imgSrc = await http.get(this.moveImg.itemRightFileNo)
// console.log(imgSrc)
img2.src = this.useImg.itemRightFileNo;
// new URL(this.moveImg.itemRightFileNo, import.meta.url).href ; // 设置第二张图片路径
// 查看第二张图片(物品)的位置
// console.log(img2)
let imgPosition = document
.getElementById('dragImg_' + this.useImg.id)
.getBoundingClientRect();
let img2Left = imgPosition.left - this.divPosition.left;
let img2Top = imgPosition.top - this.divPosition.top;
let that = this;
// console.log(this.currentItem,"111")
img2.onload = function () {
ctx.globalCompositeOperation = 'source-over'; // 设置合成模式
ctx.drawImage(img2, 0, 0, canvas.width, canvas.height); // 将第二张图片绘制到Canvas中 参数为:图片,left top width height 定位和绘制宽高
// 生成合成后的图片数据URL
that.mergedImgDataURL = canvas.toDataURL();