奇怪的HTML5 Canvas drawImage行为 [英] Strange HTML5 Canvas drawImage behaviour

查看:127
本文介绍了奇怪的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设置canvas元素的宽度和高度属性。附加canvas元素的属性(而不是CSS),尺寸应该自行更正。

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行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆