按比例调整图像大小以适合HTML5画布
Resize image proportionately to fit into HTML5 canvas
我正试图写一个jQuery插件,将有类似的功能,Flash基于Zazzle.com上的产品编辑器。我需要知道的是如何使用context.drawImage()
画布函数,我可以插入图像并调整其大小以适应画布而不会扭曲它。
图片是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 );
欢迎大家提出建设性意见。
这就是问题所在:
美元(帆布)。Attr ('id', options.id).css({width: options.id;宽度,高度:选项。高度});
当你需要直接设置宽度和高度属性时,你正在设置画布的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之前完成。
相关文章:
- JavaScript HTML5画布未显示
- html5画布动画无法正常工作
- 在HTML5画布上添加按钮和控件
- 如何在运行时在HTML5画布中绘制正方形
- Unicode字符未在HTML5画布中正确呈现
- 鼠标点击HTML5画布绘制矩形
- html5画布在同一行中写入多个字体
- HTML5画布-暂停时的运行时间
- 使用JavaScript和HTML5画布进行冲突检测
- 什么是HTML5画布标记的回退
- 如何在html5画布中绘制圆形作为单独的画布
- 如何在flash html5画布项目中动态更改文本颜色
- HTML5画布支持和Android Webview
- html5画布中的套索工具
- 什么'是在HTML5画布中创建关键事件的最佳方式
- Javascript:延迟在html5画布上循环绘制
- 如何在HTML5画布上呈现音频波形
- HTML5画布动画滑块
- 如何将 html5 画布另存为窗口 8 Metro 应用程序中的图像文件
- HTML5-画布元素&自定义光标