Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在画布中绘制图像_Javascript_Jquery_Canvas - Fatal编程技术网

Javascript 在画布中绘制图像

Javascript 在画布中绘制图像,javascript,jquery,canvas,Javascript,Jquery,Canvas,这是我的建议: 我不知道我做错了什么。我试图在画布内绘制此图像的第一块瓷砖,但什么也没有发生 function Character(x, y, speed, TilesPos, TilesRow) { this.x = x; this.y = y; this.w = 25; this.h = 25; this.sp = speed; this.Pos =

这是我的建议:

我不知道我做错了什么。我试图在画布内绘制此图像的第一块瓷砖,但什么也没有发生

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

        }

您从未设置画布的宽度和高度属性。默认大小为300x150。你在这些维度之外绘制图像,所以你看不到它。如果使用CSS调整其大小,它只会拉伸画布以适应扭曲图像的尺寸,而不会更改画布坐标系

我添加/更改了这些行

   var canvas = $('#My_Canvas')[0];
   canvas.width = 400;
   canvas.height = 400;
   var ctx = canvas.getContext("2d");
另外,如果只是使用canvas元素,则不需要jQuery,这会增加不必要的开销


另外,对于动画,我强烈建议您签出,而不是使用
setInterval
,但我正在从html设置宽度和高度,这样做:
@Sora我更新了我的答案。通过CSS设置画布宽度和高度只会扭曲画布,您必须设置画布元素本身的宽度和高度属性。此外,请确保在尝试绘制图像之前加载图像:charImg.onload=function(){draw();}charImg.src=“”@索拉,不客气。如果它能回答您的问题,我们将不胜感激。