Strange HTML5 Canvas drawImage behaviour(奇怪的 HTML5 Canvas drawImage 行为)
问题描述
我正在编写一些使用 HTML5 画布的代码.一般来说它运作良好,但现在我发现了一个非常奇怪的行为.奇怪的是它在不同的浏览器上是一致的,所以一定是我理解错了……尽管文档似乎准确地说明了我在做什么.这是代码(它是一个对象方法):
I am writing some code that uses HTML5 canvas. Generally it works well, but now I found a very strange behaviour. The weird thing is that it is consistent on different browsers, so must be that I understood the thing wrong... Despite the docs seem to say exactly what I am doing. Here is the code (it's an object method):
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;
};
在此之后,我将再次使用 jQuery 将此元素附加到页面中已经存在的 Div(空白).结果将是图像被过度拉伸,就像它的宽度的十倍......这很奇怪,因为根据我对 drawImage 的理解,它应该使用 w 和 h 值来缩放图像,并且假设 w 和 h 是画布的大小,应该很合适.
After this I'll use jQuery again to append this element to a Div that is already in the page (which is blank). The result will be that the image is overstretched like ten times it's width.... That is weird because, for what I understood of drawImage, it should use the w and h values to scale the image and given that w and h are the size of the canvas, it should fit well.
我做错了什么?是不是因为我在渲染的 DOM 树上进行绘制?
What am I doing wrong? Is it because I do the drawing off the rendered DOM tree?
推荐答案
我发现这个功能"也有点令人讨厌.似乎您不想使用 CSS 来设置画布元素的宽度和高度属性.将带有属性(而不是 CSS)的 canvas 元素附加,并且尺寸应该自行更正.
I found this "feature" as well to be a bit irksome. It seems as though you don't want to use CSS to set the width and height properties for the canvas element. Append the canvas element with attributes (rather than CSS) and the dimensions should correct themselves.
var canvas = jQuery("<canvas/>", {
'id' : this.viewId + "canvas"
});
$('#' + this.viewId).attr('height', this.height).attr('width', this.width);
这篇关于奇怪的 HTML5 Canvas drawImage 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:奇怪的 HTML5 Canvas drawImage 行为


基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01