奇怪的 HTML5 Canvas drawImage 行为

2022-01-17 00:00:00 html html5-canvas scaling 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);

相关文章