【问题标题】:Resize image proportionately to fit into HTML5 canvas按比例调整图像大小以适合 HTML5 画布
【发布时间】:2011-12-06 09:01:53
【问题描述】:

我正在尝试编写一个与 Zazzle.com 上基于 Flash 的产品编辑器具有相似功能的 jQuery 插件。我需要知道的是,如何使用 context.drawImage() 画布函数插入图像并调整其大小以适应画布而不会使它变形。

图像是 500x500 像素,画布也是如此,但由于某种原因,当我将图像尺寸设置为 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 );

也欢迎任何其他建设性的批评。

【问题讨论】:

    标签: javascript jquery html canvas drawimage


    【解决方案1】:

    这就是问题所在:

    $(canvas).attr('id', options.id).css({ width: options.width, height: 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 之前完成此操作。

    【讨论】:

      猜你喜欢
      • 2014-01-27
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 2018-07-11
      • 2017-04-29
      • 2011-01-19
      相关资源
      最近更新 更多