got*_*ch4 27 html5 scaling drawimage html5-canvas
我正在编写一些使用HTML5画布的代码.一般来说效果很好,但现在我发现了一种非常奇怪的行为.奇怪的是,它在不同的浏览器上是一致的,所以必须是我理解错误的东西......尽管文档似乎正好说明了我在做什么.这是代码(它是一个对象方法):
MyCanvas.prototype.getElement = function() {
var innerHtml = "<div></div>";
var elem = jQuery(innerHtml, {
'id' : this.viewId
});
var canvas = jQuery("<canvas/>", {
'id' : this.viewId + "canvas",
'width' : this.width,
'height' : this.height
});
var w = this.width;
var h = this.height;
jQuery(elem).append(canvas);
var imgElem = new Image();
imgElem.src = this.maskImage;
imgElem.onload = function() {
var ctx = canvas[0].getContext('2d');
ctx.drawImage(this, 0, 0, w, h);
};
return elem;
};
Run Code Online (Sandbox Code Playgroud)
在此之后,我将再次使用jQuery将此元素附加到已经在页面中的Div(这是空白).结果将是图像过度伸展,就像宽度的十倍......这很奇怪,因为对于我对drawImage的理解,它应该使用w和h值来缩放图像,并且假设w和h是画布的大小,应该很合适.
我究竟做错了什么?是因为我绘制了渲染的DOM树吗?
Bri*_*gan 56
我发现这个"功能"也有点令人讨厌.看起来好像你不想使用CSS来设置canvas元素的width和height属性.使用属性(而不是CSS)附加canvas元素,并且维度应该自行更正.
var canvas = jQuery("<canvas/>", {
'id' : this.viewId + "canvas"
});
$('#' + this.viewId).attr('height', this.height).attr('width', this.width);
Run Code Online (Sandbox Code Playgroud)