微信小游戏canvas实现图片A水平镜像翻转到图片B
2024-12-19 13:24:47
示例效果图
代码如下:
Javascript
const canvas = wx.createCanvas();
const context = canvas.getContext('2d');
const x = 150,
y = 300,
w = 100,
h = 140;
// Load the first image (Image A)
const imgA = wx.createImage();
imgA.src = ''; // 图片A路径
imgA.onload = () => {
context.drawImage(imgA, x, y, w, h);
};
// Load the second image (Image B)
const imgB = wx.createImage();
imgB.src = ''; // 图片B路径
let loop = 1;
const flipX = () => {
Math.animation(loop * 1, loop * -1, 600, 'easeInOut', (value, isEnding) => {
context.clearRect(x, y, w, h);
context.translate(x + w / 2, 0);
context.scale(value, 1);
context.translate(-(x + w / 2), 0);
if (value > 0) {
context.drawImage(imgA, x, y, w, h);
} else {
context.translate(x + w / 2, 0);
context.scale(-1, 1);
context.drawImage(imgB, -w / 2, y, w, h);
}
context.setTransform(1, 0, 0, 1, 0, 0);
if (isEnding) {
loop = -1 * loop;
}
});
};
wx.onTouchStart((e) => {
flipX();
});
End
没有了