按比例调整图像大小以适应HTML5画布

7
我正试图编写一个jQuery插件,其功能类似于Zazzle.com上基于Flash的产品编辑器。我需要知道如何使用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 );

欢迎提出任何建设性的批评意见。

1个回答

10
这是问题所在: $(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之前必须进行此操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接