1、cocos 原生截屏功能 ,保存为图片,在ios 或者java代码里可以拿到图片做分享等功能 (H5不支持saveToFile 该方法只能在原生平台上使用)
saveCanvas: function () { var size = cc.director.getWinSize(); var fileName = "result_share.jpg"; var fullPath = jsb.fileUtils.getWritablePath() + fileName; //拿到可写路径,将图片保存在本地,可以在ios端或者java端读取该文件 if (jsb.fileUtils.isFileExist(fullPath)) { jsb.fileUtils.removeFile(fullPath); } var texture = new cc.RenderTexture(Math.floor(size.width), Math.floor(size.height)); texture.setPosition(cc.p(size.width / 2, size.height / 2)); texture.begin(); cc.director.getRunningScene().visit(); //这里可以设置要截图的节点,设置后只会截取指定节点和其子节点 texture.end(); texture.saveToFile(fileName, cc.IMAGE_FORMAT_JPG); },
//截屏保存到相册 var ret = jsb.reflection.callStaticMethod("NativeOcClass", "callNativeUIWithTitle:andContent:", "cocos2d-js", fileName); @implementation NativeOcClass +(BOOL)callNativeUIWithTitle:(NSString *) title andContent:(NSString *) content { NSString* filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.png", content]; UIImage *viewImage = [UIImage imageWithContentsOfFile:filePath]; if (viewImage != nil) { UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil); UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:content delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; [alertView show]; } return true; }
2、H5版本 截图功能,截图得到的数据 生产图片资源,创建一个image 指向该图片资源,添加到document上 然后就支持浏览器的长按保存功能了,也可以做分享
saveCancas:function(){ var self = this; var canvas = document.getElementById("GameCanvas"); var href = canvas.toDataURL("image/png"); var canvas = cc.find("Canvas").getComponent(cc.Canvas); var vsbSize = cc.view.getVisibleSize(); var designSize = canvas.designResolution; console.log("balance designSize" + designSize); console.log("balance visitblSize" + vsbSize); var scaleW = vsbSize.width / designSize.width; var scaleH = vsbSize.height / designSize.height; var fitScale = Math.max(scaleW,scaleH); var gameDiv = document.getElementById('Cocos2dGameContainer');//获取div元素 var bigImg = document.createElement("img");//创建img元素 bigImg.id = 'QRCode'; bigImg.src = href;//给img标签添加图片源 bigImg.alt = 'bigImg'; bigImg.width = parseInt(gameDiv.style.width.replace(/px/, '')) * fitScale; bigImg.height = parseInt(gameDiv.style.height.replace(/px/, '')) * fitScale; bigImg.style.position = 'absolute'; bigImg.style.top = "0px";//y坐标 bigImg.style.left = parseInt(gameDiv.style.width.replace(/px/, '')) / 2 - bigImg.width / 2 + "px";//设置图片居中显示 gameDiv.appendChild(bigImg); },