我正在尝试编写一个 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 );
也欢迎任何其他建设性的批评。