在canvas与pubnub和webrtc之间成功传输数据

时间:2015-06-29 14:39:27

标签: javascript html5 canvas webrtc pubnub

我正在尝试实现一个小应用程序(例如,为了让我的主应用程序工作),当一个画布上的用户点击一个按钮时,其他用户的频道号码变化以便变得相同作为单击第一个画布上的按钮的用户(这实现如下所示,使用webrtc和pubnub!)。
问题是数据从不在对等体之间交换,因此通道永远不会改变。请帮忙!!

的index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <title>CoDoodler</title>
    <meta name="description" content="Draw">
    <meta name="author" content="Tomomi Imura  @girlie_mac">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
        <script src="http://cdn.pubnub.com/pubnub.min.js"></script>
</head>

<body>
<script>var canvas_flag = false;</script>
    <header>
        <div>
            <h1>CoDoodler</h1>
            <h2>Doodle with strangers on InterWeb!</h2>
        </div>
        <div class="bubble">
            <span id="occupancy">0</span>
            <span id="unit">doodler</span>
        </div>
    </header>

    <section id="main">
        <canvas id="drawCanvas" width="300" height="300">Canvas is not supported on this browser!</canvas>

        <section id="colorSwatch">
            <input type="radio" name="color" id="color01" data-color="gold" checked><label for="color01"></label> 
            <input type="radio" name="color" id="color02" data-color="darkorange">  <label for="color02"></label>  
            <input type="radio" name="color" id="color03" data-color="navy">        <label for="color03"></label>  
            <input type="radio" name="color" id="color04" data-color="yellowgreen"> <label for="color04"></label>  
            <input type="radio" name="color" id="color05" data-color="firebrick">   <label for="color05"></label>  
            <input type="radio" name="color" id="color06" data-color="powderblue">  <label for="color06"></label> 
        </section>
    </section>

    <footer>
        Powered by <a href="http://pubnub.com" target="_blank">PubNub</a><br>
        Read the tutorial on <a href="http://pubnub.com/blog/multiuser-draw-html5-canvas-tutorial/" target="_blank">PubNub Blog</a>
    </footer>

    <a href="https://github.com/pubnub/codoodler" target="_blank"><img class="github" style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>

    <script>
        // For history() demo, please view history.html.
        var drawHistory = false;

          var number =  Math.floor(Math.random()*999+1); //phone variable

          var string_number = number.toString();

                var pubnub = PUBNUB({
          subscribe_key: 'demo', // always required
          publish_key: 'demo'    // only required if publishing
        });


          function function1(){

                pubnub.publish({
                  channel: 'canvas_channel2000',    
                  'message' : {              
                   'canvas_channel_number':  string_number             
                  },                   
                   callback : function(m){console.log(m)}
            });
        }

        function change_the_canvas_channel_(m){

            string_number = m.canvas_channel_number;
            console.log("tora to kanali egine"+ string_number);


        }

                 pubnub.subscribe({ 
               channel: 'canvas_channel2000',
               message: function(m){change_the_canvas_channel_(m)}
               error: function (error) {
               // Handle error here
                  console.log(JSON.stringify(error));

                }
            });

    </script>
<button type="button" onclick = "function1()">Submit</button>

    <script src="js/test1.js"></script>

</body>
</html>

test1.js

  (function() {
    /* Canvas */

    var canvas = document.getElementById('drawCanvas');
    var ctx = canvas.getContext('2d');
    var color = document.querySelector(':checked').getAttribute('data-color');

    canvas.width =  300;
    canvas.height =  300;

    ctx.strokeStyle = color;
    ctx.lineWidth = '3';
    ctx.lineCap = ctx.lineJoin = 'round';

    /* Mouse and touch events */

    document.getElementById('colorSwatch').addEventListener('click', function() {
        color = document.querySelector(':checked').getAttribute('data-color');
    }, false);

    var isTouchSupported = 'ontouchstart' in window;
    var isPointerSupported = navigator.pointerEnabled;
    var isMSPointerSupported =  navigator.msPointerEnabled;

    var downEvent = isTouchSupported ? 'touchstart' : (isPointerSupported ? 'pointerdown' : (isMSPointerSupported ? 'MSPointerDown' : 'mousedown'));
    var moveEvent = isTouchSupported ? 'touchmove' : (isPointerSupported ? 'pointermove' : (isMSPointerSupported ? 'MSPointerMove' : 'mousemove'));
    var upEvent = isTouchSupported ? 'touchend' : (isPointerSupported ? 'pointerup' : (isMSPointerSupported ? 'MSPointerUp' : 'mouseup'));

    canvas.addEventListener(downEvent, startDraw, false);
    canvas.addEventListener(moveEvent, draw, false);
    canvas.addEventListener(upEvent, endDraw, false);

    /* PubNub */

    var pubnub = PUBNUB.init({
        publish_key     : 'pub-c-465c4b3b-0b7d-40de-86c5-10a9433058b5',
        subscribe_key   : 'sub-c-43a257e0-d94a-11e4-a2b8-0619f8945a4f',
        leave_on_unload : true
    });

    pubnub.subscribe({
        channel: string_number,
        callback: drawFromStream,
        presence: function(m){
            if(m.occupancy > 1){
                document.getElementById('unit').textContent = 'doodlers';
            }
            document.getElementById('occupancy').textContent = m.occupancy;
            var p = document.getElementById('occupancy').parentNode;
            p.classList.add('anim');
            p.addEventListener('transitionend', function(){p.classList.remove('anim');}, false);
        }
    });

    function publish(data) {
        pubnub.publish({
            channel: string_number,
            message: data
        });
     }

    /* Draw on canvas */

    function drawOnCanvas(color, plots) {
        ctx.strokeStyle = color;
        ctx.beginPath();
        ctx.moveTo(plots[0].x, plots[0].y);

        for(var i=1; i<plots.length; i++) {
            ctx.lineTo(plots[i].x, plots[i].y);
        }
        ctx.stroke();
    }

    function drawFromStream(message) {
        if(!message || message.plots.length < 1) return;
        drawOnCanvas(message.color, message.plots);
    }

    // Get Older and Past Drawings!
    if(drawHistory) {
        pubnub.history({
            channel  : string_number,
            count    : 50,
            callback : function(messages) {
                pubnub.each( messages[0], drawFromStream );
            }
        });
    }
    var isActive = false;
    var plots = [];

    function draw(e) {
        e.preventDefault(); // prevent continuous touch event process e.g. scrolling!
        if(!isActive) return;

        var x = isTouchSupported ? (e.targetTouches[0].pageX - canvas.offsetLeft) : (e.offsetX || e.layerX - canvas.offsetLeft);
        var y = isTouchSupported ? (e.targetTouches[0].pageY - canvas.offsetTop) : (e.offsetY || e.layerY - canvas.offsetTop);

        plots.push({x: (x << 0), y: (y << 0)}); // round numbers for touch screens

        drawOnCanvas(color, plots);
    }

    function startDraw(e) {
        e.preventDefault();
        isActive = true;
    }

    function endDraw(e) {
        e.preventDefault();
        isActive = false;

        publish({
            color: color,
            plots: plots
        });

        plots = [];
    }
})();

1 个答案:

答案 0 :(得分:0)

我发现你没有使用test1.js发布或订阅,它只是来自PubNub教程页面的画布代码,所以我忽略了js来测试你的代码。 如果你能在发布问题之前清理它会很好!

无论如何,发布和订阅确实可以正常工作。

我修改了您的代码,以便您可以在第二个用户的浏览器窗口中查看订阅的时间 -

  1. 初始化:
  2. 
    
        var pubnub = PUBNUB({
          subscribe_key: 'sub-c-...', 
          publish_key: 'pub-c-...'    
        });
    
    

    请使用您自己的subscribe_keypublish_key键,而不是您从教程中复制的键!否则,请使用&#39; demo&#39;对于两者。

    1. onclick事件发生后,您的应用会将随机数发布为字符串:
    2. 
          pubnub.publish({
            channel: 'canvas_channel2000',    
            'message' : {              
              'canvas_channel_number': string_number             
            },                   
            callback : function(m){console.log(m)}
          });
      
      1. 订阅
      2. 
        
            pubnub.subscribe({ 
              channel: 'canvas_channel2000',
              message: function(m){
                console.log(m);
              }
            });
        
        

        成功订阅邮件后,您应该在浏览器控制台上看到该对象。 上面的代码(删除了一些没有意义的代码,例如订阅中的uuid)按预期工作。

        另外,我建议你也使用调试控制台! http://www.pubnub.com/console/