在html5画布上旋转svg文件

时间:2018-02-03 18:53:10

标签: javascript html canvas

创建游戏并尝试旋转svg文件需要帮助实现

这里是构造函数

function Paperplane(width, height, xPos, yPos, image) {
this.xPos = xPos;
this.yPos = yPos;
this.speedX = 0;
this.speedY = 0;
this.width = width;
this.height = height;
this.angle = 0;
this.image = new Image();
this.image.src = image;
this.update = function() {
    //   var img = new Image();
    //  img.onload = function() {
    //     ctx.drawImage(img, xPos, yPos, width, height);
    // };
    // image.src = "../paper-droid/assets/images/paperplane.svg";
    ctx = myGameArea.context;
    ctx.drawImage(
        this.image,
        this.xPos,
        this.yPos,
        this.width,
        this.height
    );
}

}

旋转我无法开始工作的方法

Paperplane.prototype.drawRotated = function(context, xPos, yPos) {
ctx.save();
ctx.translate(this.xPos + this.width / 2, this.yPos + this.height / 2);
ctx.rotate(this.angle * Math.PI / 180);
ctx.drawImage(this.img, this.x, this.y, this.width, this.height,
                        -this.width / 2, -this.height / 2, this.width, this.height);
ctx.restore();
}

目前只是尝试使用左箭头键来调用rotate方法以使其正常工作

// Move
// keyCodes: Right => 39, left => 37, Up => 38, Back => 40, Spacebar => 32
// keydown function that will move plane sprite across game canvas
function move(e) {
// alert(e.keyCode);
if (e.which == 39) {
    plane.speedX = 5;
    // console.log("Move 5 pixels to the right")
}
if (e.which == 37) {
    plane.speedX = -5;
    plane.drawRotated();
    // console.log("Move 5 pixels to the left")
}
if (e.which == 38) {
    plane.speedY = -5;
    // console.log("Move 5 pixels up")
}
if (e.which == 40) {
    plane.speedY = 5;
    // console.log("Move 5 pixels down")
}

if (e.which == 32) {
    plane.shoot();
}

}

document.onkeydown = move;   

我在控制台上获得的错误

未捕获的TypeError:无法执行' drawImage'上 ' CanvasRenderingContext2D':提供的值不是类型'(CSSImageValue 或HTMLImageElement或SVGImageElement或HTMLVideoElement或 HTMLCanvasElement或ImageBitmap或OffscreenCanvas)' 在Paperplane.drawRotated(game.js:90) 在HTMLDocument.move(game.js:107)

1 个答案:

答案 0 :(得分:0)

声明变量的位置像这样定义

this.image = new Image();

但是在drawRotated函数中,您尝试使用名为

的变量
this.img

所以问题是图像与img的变量名称。尝试在绘图函数中使用this.image。

相关问题