cocos creator加载小游戏本地图片
onTouchEnd(event){
let texture = new cc.RenderTexture();
texture.initWithSize(cc.visibleRect.width, cc.visibleRect.height, cc.gfx.RB_FMT_S8);
this.camera.targetTexture = texture;
let width = this.capNode.width;
let height = this.capNode.height;
this._canvas = document.createElement('canvas');
this._canvas.width = width;
this._canvas.height = height;
let ctx = this._canvas.getContext('2d');
this.camera.render();
// 2. 获取指定区域的像素点信息
let size = this.capNode.getContentSize();
let pixels = new Uint8Array(size.width * size.height * 4);
let x = texture.width/2 - this.capNode.width/2;
let y = texture.height/2 - this.capNode.height/2;
let w = this.capNode.width;
let h = this.capNode.height;
let data = texture.readPixels(pixels, x, y, w, h);
// let data = texture.readPixels();
// write the render data
let rowBytes = width * 4;
for (let row = 0; row < height; row++) {
let srow = height - 1 - row;
let imageData = ctx.createImageData(width, 1);
let start = srow * width * 4;
for (let i = 0; i < rowBytes; i++) {
imageData.data[i] = data[start + i];
}
ctx.putImageData(imageData, 0, row);
}
if (cc.sys.platform === cc.sys.BYTEDANCE_GAME) {
let data = {
x: 0,
y: 0,
width: this._canvas.width,
height: this._canvas.height,
// destination file sizes
destWidth: this._canvas.width,
destHeight: this._canvas.height,
fileType: 'png',
quality: 1
}
// 临时图片
let _tempFilePath = this._canvas.toTempFilePathSync(data);
console.log(`Capture file success!${_tempFilePath}`);
let fs = tt.getFileSystemManager()
// 永久图片
fs.saveFile({
tempFilePath:_tempFilePath,
success:(res)=>{
console.log("saveFile="+res.savedFilePath)
// 加载
cc.assetManager.loadRemote(res.savedFilePath,{ext: '.png'},(err,ass)=>{
if(err){
console.log("err")
return
}
console.log("ok=>"+ass)
this.laodSpr.spriteFrame=new cc.SpriteFrame(ass);
this.player.changeHead(new cc.SpriteFrame(ass))
})
}
})
}else{
let dataURL = this._canvas.toDataURL("image/png");
let img = document.createElement("img");
img.src = dataURL;
cc.log(dataURL)
let texture2 = new cc.Texture2D();
texture2.initWithElement(img);
let sf = new cc.SpriteFrame();
sf.setTexture(texture2);
this.laodSpr.spriteFrame=sf;
this.player.changeHead(sf.clone())
}
}