更改Javascript变量而不刷新

时间:2012-01-01 04:01:03

标签: php javascript html ajax

我想知道如何在不刷新页面的情况下更改javascript中的“image.src”(好吧,不清除画布)。

我正在考虑使用类似AJAX的东西(我之前从未使用过它),但我不确定这是否是正确的道路。谁能帮助我?

这是我的代码:

<form>
Image URL:<input type="text" size="50" name="i" value="<?php echo $_REQUEST['i']?>" />
Background Color:<select name="color" >
<?php if($_REQUEST['color'] == "#000000"){ ?>
  <option value="#000000">Black</option>
  <option value="#ffffff">White</option>
  <?php }else{ ?>
    <option value="#ffffff">White</option>
    <option value="#000000">Black</option>
    <?php } ?>
</select>
<input type="submit"/> || Back to the <a href="/cloner/index.php">Home Page</a>
</form>
</div>
        <script type="text/javascript">
        var imageWidthHalf, imageHeightHalf;
        var canvas = document.createElement( 'canvas' );
        var height = window.innerHeight;
            canvas.width = window.innerWidth;
            canvas.height = height;
            canvas.style.display = 'block';
            document.body.appendChild( canvas );
            var context = canvas.getContext( '2d' );
            var image = document.createElement( 'img' );
            image.addEventListener('load', function() {
                imageWidthHalf = Math.floor( this.width / 2 );
                imageHeightHalf = Math.floor( this.height / 2 );
                document.addEventListener( 'mousemove', onMouseEvent, false );
                document.addEventListener( 'touchstart', onTouchEvent, false );
                document.addEventListener( 'touchmove', onTouchEvent, false );
            }, false );
            image.src = "<?php echo $_REQUEST['i']; ?>";
            function onMouseEvent( event ) {
                context.drawImage( image, event.clientX - imageWidthHalf, event.clientY - '50' - imageHeightHalf );
            }
            function onTouchEvent( event ) {
                event.preventDefault();
    for ( var i = 0; i < event.touches.length; i++ ) {
                    context.drawImage( image, event.touches[i].pageX - imageWidthHalf, event.touches[i].pageY - imageHeightHalf );
                }
            }
        </script>

1 个答案:

答案 0 :(得分:2)

document.querySelector('input[name="i"]').addEventListener('blur', function() {
    image.src = this.value;
}, false);