背景图上运动元素
说明:
1.保证图片只全部加载
2.保证顺序绘制
3.图片只加载一遍
let systemInfo = tt.getSystemInfoSync()
let canvas = tt.createCanvas(),
ctx = canvas.getContext('2d');
let {windowWidth,windowHeight} = systemInfo;
let imageResource = [
'https://www.xxx.com/scene1_start_bg.jpg',
'https://www.xxx.com/scene1_startBtn.png'
]
const images = {};
function loadImage(link) {
return new Promise((resolve, reject) => {
let oImg = tt.createImage();
oImg.onload = function(res){
resolve(oImg);
}
oImg.onerror = function(err){
resolve(err);
}
oImg.src = link;
oImg.url = link;
});
}
Promise.all([
loadImage(imageResource[0]),
loadImage(imageResource[1])
]).then((res) => {
res.forEach(item => {
images[item.url] = item;
});
console.log(res, images);
var nowX = 0;
var iSpeed = 2;
// 加载完成后开始绘制
requestAnimationFrame(function step() {
if(nowX<0){
iSpeed=2;
}else if(nowX>windowWidth-200){
iSpeed=-2;
}
nowX += iSpeed;
ctx.clearRect(0, 0, windowWidth, windowHeight);
ctx.drawImage(images[imageResource[0]], 0, 0, windowWidth, windowHeight);
ctx.drawImage(images[imageResource[1]], nowX, windowHeight*0.5-35,200,70);
requestAnimationFrame(step);
});
});
网友评论