繁体   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