Alice
Alice

Reputation: 424

Change Javascript Variable without refresh

I was wondering how i would go about changing "image.src" in the javascript without refreshing the page(well, without clearing the canvas).

I was thinking about using something like AJAX (i have never used it before) but i'm not sure if that is the right path to go. Could anyone help me out?

Here's my code:

<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>

Upvotes: 0

Views: 775

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 220136

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

Upvotes: 2

Related Questions