2011-10-12 6 views
6

Zazzle.comのFlashベースの製品エディタと同様の機能を持つjQueryプラグインを作成しようとしています。私が知る必要があるのは、context.drawImage()キャンバス機能を使用して、イメージを挿入し、それを歪ませることなくキャンバスに収まるようにサイズ変更する方法です。イメージをHTML5キャンバスに合わせてサイズ変更

画像は500x500pxでキャンバスですが、何らかの理由で500x500を画像の大きさに設定すると大きくなります。その他の建設的な批判も歓迎

(function($) { 

    jQuery.fn.productEditor = function(options) { 

     var defaults = { 
      'id'  : 'productEditor', 
      'width'  : '500px', 
      'height' : '500px', 
      'bgImage' : 'http://www.wattzup.com/projects/jQuery-product-editor/sampleProduct.jpg' 
     }; 


     return this.each(function() { 

      var $this = $(this) 

       var options = $.extend(defaults, options); 

      // Create canvas 
      var canvas = document.createElement('canvas'); 

      // Check if their browser supports the canvas element 
      if(canvas.getContext) { 
       // Canvas defaults 
        var context = canvas.getContext('2d'); 
        var bgImage = new Image(); 
        bgImage.src = options.bgImage; 
        bgImage.onload = function() {   
        // Draw the image on the canvas 
        context.drawImage(bgImage, 0, 0, options.width, options.height); 
       } 

       // Add the canvas to our element 
       $this.append(canvas); 
       // Set ID of canvas 
       $(canvas).attr('id', options.id).css({ width: options.width, height: options.height }); 




      } 
      // If canvas is not supported show an image that says so 
      else { 

       alert('Canvas not supported!'); 


      } 


     }); 

    }; 
})(jQuery); 

はここで、これまでに私の完全なコードです。

答えて

9

これは問題である。

$(キャンバス).ATTR( 'ID'、options.id)の.css({幅:options.width、高さ:options.height})。

幅と高さの属性を直接設定する必要がある場合は、キャンバスのCSSの幅/高さを設定します。描画された画像を歪ませていない、キャンバス自体を歪めている。キャンバスはまだ300x150(デフォルト)であり、単にCSS拡張されて500x500になっています。今すぐ300x150のストレッチキャンバスに500x500のイメージを描画しています。

あなたは実行する必要があります。

var defaults = { 
     'id'  : 'productEditor', 
     'width'  : '500', // NOT 500px, just 500 
     'height' : '500', // NOT 500px, just 500 
     'bgImage' : 'http://www.wattzup.com/projects/jQuery-product-editor/sampleProduct.jpg' 
    }; 

... 

// Create canvas 
var canvas = document.createElement('canvas'); 
canvas.width = options.width; 
canvas.height= options.height; 

... 

$(canvas).attr('id', options.id); // DON'T change CSS width/height 

注これはdrawImageメソッドを使用して前に行う必要がありますので、キャンバスの幅や高さを変更すると、それをクリアしていること。

関連する問題