我有以下JS函数,它返回一个Image对象(随机绘制),我可以放在页面的某个位置。
function shipIt(w,h) {
var img = new Image();
// This function generates the image through a little complex (messy) random logic
img.src = wing(w, h / 2, 2, 4).toDataURL('image/png');
// This section creates a mirror of the above image and sews em together
var cvs1 = document.createElement('canvas');
var ctx1 = cvs1.getContext('2d');
cvs1.width = w;
cvs1.height = h;
var img1 =new Image();
img.onload = function() {
ctx1.drawImage(img, 0, h / 2);
ctx1.save();
ctx1.translate(0, h / 2);
ctx1.scale(1, -1);
ctx1.drawImage(img, 0, 0);
ctx1.restore();
console.log('loaded!!');
img1.src = cvs1.toDataURL('image/png');
console.log('url taken!!');
};
console.log('trying to load!!');
console.log('will return now!!');
// This is not returning the img correctly
return img1;
}
当我尝试将其放入img元素时,我没有正确看到图像,因为返回语句甚至在图像加载之前执行。
有没有办法解决这个问题?