2011-11-16 72 views
-1

嘗試調整圖像大小或更改顏色。圖像閃爍:更新時圖像保持閃爍

Click here to see a live example(選擇字體然後單擊更新)

PHP:

<?php 
// Set the content-type 
header('Content-Type: image/png'); 

// Create the image 
$im = imagecreatetruecolor(400, 64); 

// Create some colors 
$white = imagecolorallocate($im, 255, 255, 255); 
$grey = imagecolorallocate($im, 128, 128, 128); 
$black = imagecolorallocate($im, 0, 0, 0); 
imagefilledrectangle($im, 0, 0, 399, 64, $white); 

// The text to draw 
$text = $_GET['t']; // text 
// Replace path by your own font path 
$font = 'fonts/' . $_GET['f'] . '.ttf'; // font 

$color = $_GET['c']; 
$red = hexdec(substr($color, 0, 2)); 
$green = hexdec(substr($color, 2, 2)); 
$blue = hexdec(substr($color, 4, 2)); 

$font_color = imagecolorallocate($im, $red, $green, $blue); 

$size = $_GET['s']; 

// Add the text 
imagettftext($im, $size, 0, 5, 30, $font_color, $font, $text); 

// Using imagepng() results in clearer text compared with imagejpeg() 
imagepng($im); 
imagedestroy($im); 
?> 

JS:

$(function() 
     { 
      $.farbtastic('#colorpicker', function(color) 
      { 
       $('#color').val(color); 
       updateImage(); 
      }); 

      $('#color').blur(function() 
      { 
       $.farbtastic('#colorpicker').setColor($(this).val()); 
       updateImage(); 
      }); 

      $('#update-btn').click(function() 
      { 
       updateImage(); 
      }); 

     }); 

     function updateImage() 
     { 
      $('.sample-text').attr('style', 'background:url(preview.php?s='+$('#font-size').val()+'&c='+$('#color').val().substr(1)+'&f='+$('#font').val()+'&t=' + $('#sample-text').val().replace(' ', '+') + ')'); 
     } 

     function update(value) 
     { 
      $('#range-display').text(value); 
      updateImage(); 
     } 

HTML:

<div> 
      <select id="font"> 
       <option>Choose a Font</option> 
       <option value="dandy">Dandy</option> 
       <option value="wtf">Pixel Font</option> 
      </select> 
      <input id="font-size" type="range" min="14" max="70" value="25" onchange="update(this.value)" /><span id="range-display">25</span> 
      <input type="text" id="sample-text" placeholder="Sample text" /> 
      <input type="button" value="Update" id="update-btn" /> 
      <div id="colorpicker"></div> 
      <input type="text" id="color" name="color" value="#123456" /> 
      <div class="sample-text"></div> 
     </div> 

正如你所看到的,一旦更新了尺寸和顏色,它會閃爍。我怎麼能阻止呢?

+0

我在FF \ chrome \ IE – 2011-11-16 02:01:43

+0

hm上沒有閃爍,嘗試在更新後更改大小,或更新後更改顏色。 – user1042002

+0

因爲它沒有在客戶端繪製 - 它必須提出請求,處理圖像然後發回。 –

回答

2

您不斷更新background屬性,因此必須爲調整大小的每個像素再次獲取圖像。顯然,它不能立即做到,所以你會閃爍。

取而代之,請嘗試更改background-size,並設置setTimeout以不同大小更新背景圖像。你可能仍然會有短暫的閃爍,但沒有什麼比現在更糟。您還將節省大量的帶寬。

+0

我唯一能想到添加的其他方法是通過JavaScript創建圖像(將其加載到緩存中),然後將其交換出去。也可以消除閃光燈。 有關檢測圖像加載的一些細節在jQuery論壇上: http://forum.jquery.com/topic/simple-image-load-detection-with-load – keif