vue3+websocket+canvas刷新图片,实现直播功能demo

<template>
    <div class="Writing">
        <div class="writing_top">
            <button id="button" @click="changeValue('00-15-5D-10-82-1E', value1 ? 102 : 101 )" :disabled="!socketStatus">
                {{value1 ? '暂停' : '开始'}}
            </button>
            <div>
                <canvas id="c1" width="1000" height="800" style='border:1px solid pink' ref='canvas' />
            </div>
        </div>
    </div>
</template>

<script setup>
    import { onMounted, ref, watch, onBeforeUnmount } from 'vue'

    let value1 = ref(false);
    let ctx = ref();
    let img = new Image()
    const canvas = ref();
    const initContext = () => {
        ctx = canvas.value.getContext('2d');
        img.src = new URL('../assets/404.jpg',
            import.meta.url).href//缺省图片
        img.onload = (e) => ctx.drawImage(img, 0, 0, 1000, 800)
    }

    let socket = null
    let socketStatus = ref(false);
    const initSocket = () => {
        socket = new WebSocket("ws://192.168.6.13:33500/websocket/123");

        socket.onopen = (evt) => {
            socketStatus.value = true
            console.log("connect: websocket 连接成功!");
        };
        socket.onmessage = (evt) => {
            img.src = evt.data
            if (value1.value) ctx.drawImage(img, 0, 0, 1000, 800)
        };
        socket.onClose = (evt) => {
            socketStatus.value = false
            console.log("close: websocket 断开连接!");
        };
        socket.onerror = () => {
            socketStatus.value = false
            let rec = 0
            console.log("websocket连接错误!尝试重新连接");
            if (socketStatus.value) { // 如果已经连上就不在重连了
                clearTimeout(rec)
                rec = 0
                return;
            }
            rec = setTimeout(function() {
                initSocket();
            }, 10000); // 延迟10秒重连  避免过多次过频繁请求重连
        };
    }

    const changeValue = (PC_ID, Api) => {

      value1.value = !value1.value
      let obj = {
            Api,
                    Data: {
                        PC_ID
                    }
                }
     console.log(obj) 
     socket.send(JSON.stringify(obj))

     if (!value1.value) {
        img.src
= new URL('../assets/404.jpg', import.meta.url).href
        ctx.drawImage(img,
0, 0, 1000, 800)
     }
  }
onMounted(()
=> { initContext(); initSocket() })

// 组件被销毁之前 onBeforeUnmount(() => { socket.close() // 关闭连接 socket = null // 销毁 websocket 实例对象 })

</script>

 

posted @ 2023-02-28 13:47  HelpYourself!  阅读(267)  评论(0编辑  收藏  举报