在for循环中绘制图片,位置无法正常显示,只添加一个不循环的时候能正常显示,多次刷新,图片会落在不同的地方。代码如下:
wxml的代码:
<canvas class="box" canvas-id="myCanvas"
style="width: {{myCanvasWidth}}px; height: {{myCanvasHeight}}px; margin: 0 auto"></canvas>
js代码:
data: {
fillColor: "#e7e7e7",
lineColor: "#000000",
lineWidth: 4,
holesImg: "../../images/door.png"
},
onReady: function (e) {
this.getData();
let pointDOT= this.data.pointDOT;
const ctx = wx.createCanvasContext('myCanvas');
// 构件
for(let hole in this.data.holes){
let angel = parseFloat(this.data.holes[hole].rotation.z); //旋转角度
let holeWidth = this.data.holes[hole].width
let holePosition = this.scalePoint(this.data.holes[hole].position) //缩放后的位置
let self = this;
this.getImgSize(holeWidth).then((data)=>{
console.log(holePosition)
let rotatePosition = self.rotatePoint(holePosition.x, holePosition.y,data.w,data.h,angel,this.data.holes[hole].itemType)
ctx.translate(rotatePosition.x, holePosition.y)
console.log("旋转角度:"+angel)
ctx.rotate(angel * Math.PI / 180)
ctx.drawImage(this.data.holesImg, 0, 0, parseFloat(data.w), parseFloat(data.h));
ctx.draw(true);
ctx.translate(-rotatePosition.x, -holePosition.y) //还原原点坐标
ctx.rotate(-angel * Math.PI / 180) //还原旋转角度
});
}
},
// 画布中构件尺寸 宽* 高
getImgSize(holeWidth){
let scaleNum = this.data.scaleNum
let self = this;
return new Promise(function(resolve, reject){
wx.getImageInfo({
src: self.data.holesImg,
complete: (res) => {
const height = res.height * holeWidth / res.width; //构件高
let scaleH = self.fixed(height/scaleNum);
let scaleW = self.fixed(holeWidth/scaleNum);
let size = { w: scaleW , h: scaleH}
resolve(size)
}
})
})
},
其中输出的坐标和旋转角度都没有问题:
{x: 223.92, y: 98.02} 旋转角度:27.083475
{x: 245.32, y: 309.76} 旋转角度:179.999969
{x: 176.86, y: 377.09} 旋转角度:-89.999992
{x: 201.22, y: 435.89} 旋转角度:-143.130127
{x: 176.86, y: 377.09} 旋转角度:-89.999992
请求指导~~