当前位置: 首页 > wzjs >正文

绍兴网站建设08kejiwordpress 调用接口

绍兴网站建设08keji,wordpress 调用接口,平安建设宣传音频免费下载网站,织梦网站建设案例创建一个场景 在 Cocos Creator 中,我们将从接口获取的图片 URL 列表动态创建图片节点并显示在页面上。使用 assetManager.loadRemote 来加载这些图片并显示。 目录结构如下 为按钮button和文本Lable挂载ts脚本 运行界面 图片上传测试 背景会变成上传的图片 以下是…

创建一个场景

在 Cocos Creator 中,我们将从接口获取的图片 URL 列表动态创建图片节点并显示在页面上。使用 assetManager.loadRemote 来加载这些图片并显示。

目录结构如下

为按钮button和文本Lable挂载ts脚本

运行界面

图片上传测试

背景会变成上传的图片

以下是操作步骤的详细说明,帮助你将从后端获取的图片展示在 Cocos Creator 页面上。

操作步骤

前提条件
  1. 后端已实现图片上传接口,并能够返回图片的 URL 列表。

  2. 使用 Cocos Creator 进行开发,确保项目已经启动并且可以正常运行。


步骤 1:创建容器 Node 用于显示图片

  1. 在 Cocos Creator 编辑器中,首先创建一个容器 Node 用于放置加载的所有图片。

    • Hierarchy 窗口中,右键点击空白区域,选择 Create -> Node,并将其命名为 ImageContainer

    • 该容器 Node 将用来显示所有加载的图片。

  2. 设置容器的尺寸:

    • Inspector 窗口中,可以调整容器的尺寸、位置等,使其适合放置多个图片。


步骤 2:创建脚本并绑定到容器 Node

  1. 在 Cocos Creator 中,创建一个新的 TypeScript 脚本 文件。

    • Assets 窗口中,右键点击,选择 Create -> TypeScript,并命名为 DisplayImages.ts

  2. 打开脚本并将以下代码粘贴进去:

import { _decorator, Component, Node, Sprite, SpriteFrame, Texture2D, Button, assetManager } from 'cc';
const { ccclass, property } = _decorator;@ccclass('ImageUpload')
export class ImageUpload extends Component {@property(Node)imageNode: Node = null!;  // 用于显示图片的节点@property(Button)uploadButton: Button = null!;  // 上传按钮@property(String)imageUrl: string = '';  // 图片 URLstart() {// 给按钮添加点击事件this.uploadButton.node.on('click', this.onUploadButtonClick, this);}// 点击按钮选择文件并上传onUploadButtonClick() {// 创建一个 input 元素来选择图片文件const input = document.createElement('input');input.type = 'file';input.accept = 'image/png, image/jpeg';  // 只允许选择 PNG 和 JPG 文件// 当选择文件后触发input.onchange = (event: Event) => {const fileInput = event.target as HTMLInputElement;if (fileInput.files && fileInput.files[0]) {const file = fileInput.files[0];this.uploadImage(file);}};// 触发文件选择框input.click();}// 上传文件到后端async uploadImage(file: File) {const formData = new FormData();formData.append('file', file);try {// 发送文件到后端const response = await fetch('http://localhost:9638/photo/upload', {method: 'POST',body: formData,});if (!response.ok) {throw new Error('上传失败');}// 获取返回的图片 URLconst imageUrl = await response.text();console.log('上传成功,图片 URL:', imageUrl);// 使用上传后的图片 URL 来加载并显示图片this.imageUrl = imageUrl;  // 存储返回的图片 URLthis.loadImageFromServer(imageUrl);  // 下载并显示图片} catch (error) {console.error('文件上传失败:', error);}}// 从服务器加载并显示图片loadImageFromServer(imageUrl: string) {console.log(`尝试加载图片:${imageUrl}`);  // 添加调试日志// 使用 assetManager.loadRemote 来加载远程图片assetManager.loadRemote(imageUrl, (err, imageAsset) => {if (err) {console.error('加载图片失败:', err);return;}if (!imageAsset) {console.error('加载的图片资产无效');return;}console.log('图片加载成功');// 获取 Node 上的 Sprite 组件let sprite = this.imageNode.getComponent(Sprite);if (!sprite) {// 如果没有 Sprite 组件,添加一个sprite = this.imageNode.addComponent(Sprite);console.log('添加了 Sprite 组件');}// 创建 SpriteFrame 并将纹理设置给它const spriteFrame = new SpriteFrame();const texture = new Texture2D();texture.image = imageAsset;  // 使用 imageAsset 的纹理spriteFrame.texture = texture;// 将 SpriteFrame 设置到 Sprite 组件sprite.spriteFrame = spriteFrame;console.log('SpriteFrame 设置成功');});}
}
  1. DisplayImages 脚本绑定到场景中的一个空 Node 节点(例如,创建一个空节点 DisplayImagesNode 来挂载脚本)。

    • 右键点击 DisplayImagesNode,选择 Add Component -> Scripts -> DisplayImages

  2. Inspector 窗口中的 DisplayImages 脚本组件部分,将 imageContainer 设置为步骤 1 中创建的 ImageContainer 节点。


步骤 3:从后端获取图片 URL

  1. 假设你的后端接口是 GET /getAllUserAvatar,返回的数据是一个包含图片 URL 数组的 JSON。你可以手动填充 URL 或从后端动态获取。

    • 如果你使用动态获取 URL,可以在 start 方法中使用 fetch 请求获取图片 URL。以下是从后端获取图片 URL 的代码示例:

package com.example.demo.controller;import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;@RestController
@RequestMapping("/photo")
public class ImagineController {private static final Logger logger = LoggerFactory.getLogger(ImagineController.class);@Value("${files.upload.path}")private String fileUploadPath;@PostMapping("/upload")public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) {try {if (file.isEmpty()) {return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty");}String originalFilename = file.getOriginalFilename();String type = FileUtil.extName(originalFilename);long size = file.getSize();File uploadParentFile = new File(fileUploadPath);if (!uploadParentFile.exists()) {uploadParentFile.mkdirs();}String uuid = IdUtil.fastSimpleUUID();String fileUUID = uuid + StrUtil.DOT + type;File uploadFile = new File(fileUploadPath + fileUUID);file.transferTo(uploadFile);String url = "http://localhost:9638/photo/" + fileUUID;logger.info("File uploaded successfully: {}", url);return ResponseEntity.ok(url);} catch (IOException e) {logger.error("Failed to upload file", e);return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file");}}@GetMapping("/{url}")public void download(@PathVariable String url, HttpServletResponse response) {try {File uploadFile = new File(fileUploadPath + url);if (!uploadFile.exists()) {response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");return;}try (ServletOutputStream os = response.getOutputStream()) {response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(url, "UTF-8"));response.setContentType("application/octet-stream");os.write(FileUtil.readBytes(uploadFile));os.flush();}logger.info("File downloaded successfully: {}", url);} catch (IOException e) {logger.error("Failed to download file", e);try {response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to download file");} catch (IOException ex) {logger.error("Failed to send error response", ex);}}}
}

步骤 4:调整图片显示布局

  • 你可以通过调整 imageContainer 的布局,使得所有图片可以在屏幕上以合适的方式排列。

  • 可以通过为图片节点设置 spacing 或通过编写自定义布局脚本来调整图片的间距和排列方式。


步骤 5:运行测试

  1. 启动后端服务:确保后端接口正确返回图片 URL 列表。

  2. 运行 Cocos Creator 项目:点击 Play 按钮启动项目。

    • 前端将从后端获取所有图片 URL 并逐一显示在界面上。


总结

  1. 创建容器:在 Cocos Creator 中创建一个用于显示图片的容器 Node。

  2. 编写脚本:编写一个脚本来从后端获取图片 URL,并通过 assetManager.loadRemote 加载图片。

  3. 显示图片:通过 Sprite 组件将图片显示在页面上。

  4. 调试与测试:确保后端接口返回图片 URL,并在前端显示所有图片。


文章转载自:

http://jtgswwr5.nhpgm.cn
http://31IEWSOU.nhpgm.cn
http://HsTRk2Mo.nhpgm.cn
http://YGHWim7R.nhpgm.cn
http://fKOvqb7B.nhpgm.cn
http://uxuSBQTe.nhpgm.cn
http://hoYpGkP7.nhpgm.cn
http://su4OyOGP.nhpgm.cn
http://0Vu15yrJ.nhpgm.cn
http://QlqinXRT.nhpgm.cn
http://XlN034P3.nhpgm.cn
http://a3YD3Jdd.nhpgm.cn
http://dii7BbNV.nhpgm.cn
http://cM6rLPrN.nhpgm.cn
http://Lshhmtk9.nhpgm.cn
http://N7UyX1vO.nhpgm.cn
http://4wr8rpus.nhpgm.cn
http://88NmHEVT.nhpgm.cn
http://RwM02xGi.nhpgm.cn
http://uQRqhIwz.nhpgm.cn
http://nH2wYtqK.nhpgm.cn
http://obhoCnWI.nhpgm.cn
http://z6wsu30B.nhpgm.cn
http://4sth4JN9.nhpgm.cn
http://Gnp5Jujv.nhpgm.cn
http://X4iD8B0q.nhpgm.cn
http://rnuFlDWK.nhpgm.cn
http://UBpZnWMF.nhpgm.cn
http://ypOMuTIU.nhpgm.cn
http://ntqFISuV.nhpgm.cn
http://www.dtcms.com/wzjs/730906.html

相关文章:

  • 婚庆公司网站php源码韩国购物网站模板
  • 男学网站开发成都十大装修品牌装修公司
  • 苏州做商城网站营销推广公司
  • 佛山中小企业网站建设app开发运营需要多少钱
  • 深圳住房与建设网站南京做网站建设搭建的公司
  • 企业门户网站建设网站建设公司小猫建站
  • 东莞便宜做网站网站推广模式
  • 石家庄个人谁做网站云岭先锋网站是哪家公司做的
  • 淄博网站开发找网泰wordpress win主机伪静态
  • 什么网站发布找做效果图的网站规划对网站建设起到
  • 一元购网站建设多少钱城阳网站建设
  • 淄博网站排名优化公司网站备案 视频
  • 网站建设俄语虚拟主机怎么建网站
  • 网站简繁转换代码东盟建设工程有限公司网站
  • 太原免费网站建设湖南百度推广开户
  • 同城可以做别人一样的门户网站吗专业营销型网站定制
  • 软件技术 网站建设教程怎么查工程项目信息
  • 网站建设竞品分析基于jsp的购物网站开发
  • 合肥做网站的公司有哪些湖南省第四工程公司官网
  • 推广赚钱方法南京做网站优化价格
  • vs进行网站建设企业网站flash
  • 泰州网站排名seo外贸网站做几种产品
  • 上海网站营销怎么样网络营销论文3000字
  • 如何给一个网站做优化seo资料
  • 建站平台转型网站建设的方向和任务
  • 信息推广网站点不开的那种怎么做单页面 网站
  • 买网站需要注意什么物流运输做网站的素材
  • 网站权限设计wordpress 实现页面重定向
  • 做网站用php如何学习网页源码提取工具
  • 金湖网站建设html5网页制作源代码