6
我正在嘗試編寫一個jQuery插件,該插件將具有與Zazzle.com上基於Flash的產品編輯器類似的功能。我需要知道的是,使用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);
其他任何建設性的批評,也受到歡迎。