Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

html - Strange HTML5 Canvas drawImage behaviour

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;
    };

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.

What am I doing wrong? Is it because I do the drawing off the rendered DOM tree?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...