9

ArkUI JS AI 作诗之滚动诗句

 2 years ago
source link: https://os.51cto.com/article/715075.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

ArkUI JS AI 作诗之滚动诗句-51CTO.COM

ArkUI JS AI 作诗之滚动诗句
作者:狼哥Army 2022-07-28 14:26:11
HarmonyOS ArkUI应用开发之AI作诗,根据输入的藏头诗关键字或诗的第一句,通过调用AI接口自动生成诗,然后将返回的诗按照句号切割为数组,使用Marquee标签滚动诗句。
72a181710b18e6961b7791f74a0f879439b43e.png

​想了解更多关于开源的内容,请访问:​

​51CTO 开源基础软件社区​

​https://ost.51cto.com​

HarmonyOS ArkUI应用开发之AI作诗,根据输入的藏头诗关键字或诗的第一句,通过调用AI接口自动生成诗,然后将返回的诗按照句号切割为数组,使用Marquee标签滚动诗句,由于一句诗句长度不够,不能滚动,在后面使用空格补上长度,使诗句可以滚动。

ArkUI JS AI作诗之滚动诗句-开源基础软件社区

开发工具:DevEco Studio 3.0 Beta4

SDK:HarmonyOS SDK API Version 8

  1. 由于调用AI接口生成诗,通过网络获取数据。
    需要权限: ohos.permission.INTERNET。
    之前我们都是直接在config.json代码模式添加权限的,最新开发工具可以在图形化下添加:
ArkUI JS AI作诗之滚动诗句-开源基础软件社区

新版本开发工具的预览器下,也支持网络请求数据了,从上面效果图就可以看出,是在预览器下录制的效果。

  1. 界面相对比较简单,就把关键标签加上注释,HML代码如下:
<div class="container">
    <!-- 藏头诗 -->
    <div class="column" style="height: 30%; border-bottom: 2px solid #ccc;">
        <!-- 标题一 -->
        <text class="title">
            {{ $t('strings.titleOne') }}
        </text>
        <!-- 操作区域 -->
        <div class="input-item">
            <input type="text" value="{{inputOne}}" onchange="textChangeOne"></input>
            <input type="button" value="AI生成藏头诗" onclick="onClickOne"></input>
        </div>
        <!-- 藏头诗滚动区域 -->
        <div class="desc" onclick="onMarqueeOne">
            <marquee id="oneMarquee{{$idx}}" for="{{poetryOne}}">{{$item}}</marquee>
        </div>
    </div>
    <!-- 输入第一句诗 -->
    <div class="column" style="height: 70%;">
        <!-- 标题二 -->
        <text class="title">
            {{ $t('strings.titleTwo') }}
        </text>
        <!-- 操作区域 -->
        <div class="input-item">
            <input type="text" value="{{inputTwo}}" onchange="textChangeTwo"></input>
            <input type="button" value="AI生成整首诗" onclick="onClickTwo"></input>
        </div>
        <!-- 整首诗滚动区域 -->
        <div class="desc" onclick="onMarqueeTwo">
            <marquee id="twoMarquee{{$idx}}" for="{{poetryTwo}}">{{$item}}</marquee>
        </div>
    </div>
</div>
  1. CSS代码如下:
/**
最外面容器样式
*/
.container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    padding: 20px;
}
/**
藏头诗与整首诗内布局样式
*/
.column {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    width: 100%;
}
/**
标题
*/
.title {
    font-size: 60px;
    text-align: center;
    width: 100%;
    margin: 20px;
}
/**
文本框和按钮布局
*/
.input-item {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: stretch;
    margin-bottom: 10px;
}
/**
文本框宽度为55%
*/
input:first-child {
    width: 55%;
}
/**
诗显示区域
*/
.desc {
    padding-top: 20px;
    padding-bottom: 20px;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
}
/**
滚动文本底内边距10像素
*/
marquee {
    padding-bottom: 10px;
}
  1. JS代码如下:
import fetch from '@system.fetch';
import prompt from '@system.prompt';
export default {
    data: {
        flagOne: false,
        flagTwo: false,
        inputOne: '我爱祖国',
        inputTwo: '沁园春雪',
        poetryOne: [],
        poetryTwo: []
    },
    /**
     * 获取藏头诗文本框内容
     * @param e
     */
    textChangeOne(e) {
        // 赋值给变量
        this.inputOne = e.text;
    },
    /**
     * 获取输入第一句诗文本框内容
     * @param e
     */
    textChangeTwo(e) {
        // 赋值给变量
        this.inputTwo = e.text;
    },
    /**
     * 生成藏头诗事件
     * @param res
     */
    onClickOne() {
        // 去掉文本框空格和换行符
        this.inputOne = this.inputOne.replace(/[\s]+/g, "").replace(/\n/g, "").replace(/\r/g, "");
        // 当文本框为空时,温馨提示,并阻止往执行
        if (this.inputOne === "") {
            prompt.showDialog({
                message: "不能为空,请输入汉字",
                duration: 3000,
                bottom: '80%'
            })
            return;
        }
        // 封装URL
        var url = "https://py.myie9.com/cangtoutest/"+this.inputOne;
        var that = this;
        fetch.fetch({
            url: url,
            method: 'GET',
            responseType: 'text',
            success: function(res) {
                console.log('xx' + JSON.stringify(res));
                // 返回错误码时,温馨提示
                if(res.code == 500) {
                    prompt.showToast({
                        message: "请输入至少4个不同的汉字",
                        duration: 3000,
                        bottom: '80%'
                    })
                    return;
                }
                // 温馨提示生成成功
                prompt.showToast({
                    message: "藏头诗生成成功",
                    duration: 3000,
                    bottom: '80%'
                })
                // 获取返回的数据
                var descOne = res.data;
                // 把返回的字符串数据,按照句号切分为数组
                var descOneArray = descOne.split("。");
                console.log('xx' + descOne)
                // 清空储存诗数组
                that.poetryOne = []
                // 固定行字符长度为50
                var rowLen = 50;
                for (var index = 0; index < descOneArray.length; index++) {
                    if(descOneArray[index] === '') {
                        continue;
                    }
                    // 在每行诗后面加上句号
                    var str = descOneArray[index] + "。";
                    // 当前行诗的字符长度
                    var currentLen = str.length;
                    // 如果长度少于50个字符,补上空格(为什么要补上空格,长度不够时, Marquee是不会滚动的)
                    if(currentLen < rowLen) {
                        for(var i=0; i< rowLen - currentLen; i++) {
                            str += " ";
                        }
                    }
                    // 存储到藏头诗数组
                    that.poetryOne.push(str)
                }
            },
            fail: function(err) {
                // 出现错误时,温馨提示
                prompt.showToast({
                    message: "生成失败,请重新生成",
                    duration: 3000,
                    bottom: '80%'
                })
            }
        })
    },
    /**
     * 生成整首诗事件
     * @param res
     */
    onClickTwo() {
        // 去掉文本框空格和换行符
        this.inputTwo = this.inputTwo.replace(/[\s]+/g, "").replace(/\n/g, "").replace(/\r/g, "");
        // 当文本框为空时,温馨提示,并阻止往执行
        if (this.inputTwo === "") {
            prompt.showToast({
                message: "不能为空,请输入一句诗",
                duration: 3000,
                bottom: '50%'
            })
            return;
        }
        // 封装URL
        var url = "https://py.myie9.com/xuxietest/"+this.inputTwo;
        var that = this;
        fetch.fetch({
            url: url,
            method: 'GET',
            responseType: 'text',
            success: function(res) {
                console.log('xx' + JSON.stringify(res));
                // 返回错误码时,温馨提示
                if(res.code == 500) {
                    prompt.showToast({
                        message: "整首诗生成失败",
                        duration: 3000,
                        bottom: '50%'
                    })
                    return;
                }
                // 温馨提示生成成功
                prompt.showToast({
                    message: "整首诗生成成功",
                    duration: 3000,
                    bottom: '50%'
                })
                // 在每行诗后面加上句号
                var descTwo = res.data;
                // 把返回的字符串数据,按照句号切分为数组
                var descTwoArray = descTwo.split("。");
                console.log('xx' + descTwo)
                // 清空储存诗数组
                that.poetryTwo = []
                // 固定行字符长度为50
                var rowLen = 50;
                for (var index = 0; index < descTwoArray.length; index++) {
                    if(descTwoArray[index] === '') {
                        continue;
                    }
                    // 在每行诗后面加上句号
                    var str = descTwoArray[index] + "。";
                    // 当前行诗的字符长度
                    var currentLen = str.length;
                    // 如果长度少于50个字符,补上空格(为什么要补上空格,长度不够时, Marquee是不会滚动的)
                    if(currentLen < rowLen) {
                        for(var i=0; i< rowLen - currentLen; i++) {
                            str += " ";
                        }
                    }
                    // 存储到整首诗数组
                    that.poetryTwo.push(str)
                }
            },
            fail: function(err) {
                // 出现错误时,温馨提示
                prompt.showToast({
                    message: "生成失败,请重新生成",
                    duration: 3000,
                    bottom: '50%'
                })
            }
        })
    },
    /**
     * 控制藏头诗滚动与暂停
     */
    onMarqueeOne() {
        // 由于把返回的整首诗,按句号分开,赋值给不同的Marquee,这里循环处理滚动或暂停
        for (var i = 0; i < this.poetryOne.length; i++) {
            if(!this.flagOne){
                this.$element('oneMarquee'+i).stop();
            }else{
                this.$element('oneMarquee'+i).start();
            }
        }
        // 切换状态
        this.flagOne = !this.flagOne
    },
    /**
     * 控制整首诗滚动与暂停
     */
    onMarqueeTwo() {
        // 由于把返回的整首诗,按句号分开,赋值给不同的Marquee,这里循环处理滚动或暂停
        for (var i = 0; i < this.poetryTwo.length; i++) {
            if(!this.flagTwo){
                this.$element('twoMarquee'+i).stop();
            }else{
                this.$element('twoMarquee'+i).start();
            }
        }
        // 切换状态
        this.flagTwo = !this.flagTwo;
    }
}

项目虽简单,但可以让我们学习到HarmonyOS JS开发,原来和其它小程序,html5开发一样简单,有了基础知识了,结合官方API文档,就可以做出更多有趣的项目。

​想了解更多关于开源的内容,请访问:​

​51CTO 开源基础软件社区​

​https://ost.51cto.com​​。

责任编辑:jianghua 来源: 鸿蒙社区
zanpc.bd208a1.pngzanpchover.fdd60ba.png
weixin.23cd8b3.png 分享到微信
weibo.16d6b4f.png 分享到微博

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK