簡體   English   中英

在畫布內繪制圖像

[英]Drawing an image inside canvas

這是我的jsfidle: http : //jsfiddle.net/2YDNq/

我不知道我在做什么錯。 我正在嘗試在畫布內繪制此圖像的第一個圖塊,但沒有任何反應。

function Character(x, y, speed, TilesPos, TilesRow) {
            this.x = x;
            this.y = y;
            this.w = 25;
            this.h = 25;
            this.sp = speed;
            this.Pos = TilesPos;
            this.Row = TilesRow;
            this.MaxTiles = 11;
        }

        Character.prototype.draw = function () {
            ctx.drawImage(charImg, this.Pos * this.w, this.w * this.Row, this.w, this.h, this.x, this.y, this.w, this.h);
        };
        var character = new Character(cw / 2, (ch - 25), 1, 1, 1);
        function Draw() {
            ctx.clearRect(0, 0, cw, ch);
            if (charImg.complete){
                character.draw();
            }

        }

您永遠不會設置畫布的width和height屬性。 默認尺寸為300x150。 您要在這些尺寸之外繪制圖像,這就是為什么看不到它的原因。 如果使用CSS調整其大小,則它只會拉伸畫布以適應扭曲圖像的尺寸,而不會更改畫布的坐標系。

現場演示

我添加/更改了這些行。

   var canvas = $('#My_Canvas')[0];
   canvas.width = 400;
   canvas.height = 400;
   var ctx = canvas.getContext("2d");

另外,如果您僅使用canvas元素,則不需要jQuery,這會增加不必要的開銷。

同樣對於動畫,而不是使用setInterval我強烈建議您檢出requestAnimationFrame

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM