在javascript,canvas中滚动来获取整个图像

时间:2015-11-06 21:25:53

标签: javascript canvas

请考虑以下事项:

enter image description here

您看到的所有内容都会呈现在HTML 5画布上。正如您所见,此图像滚动。当角色在地图上走动时会滚动。

考虑实际图像:

enter image description here

此图像是角色走过的地图的实际图像。现在考虑以下代码:

matches

此代码在运行时会创建以下图像:

enter image description here

代码有效,但正如您所看到的,我们只从画布中获取当前可见图像。现在这个渲染方式都使用了Pixi.js,所以我的问题是:

有没有办法在不滚动的情况下获得整个图像?

canvas api有这样的东西吗?唯一的另一种方法是滚动和缝合,但我不知道该怎么做,我可以让它滚动,但我不知道何时停止,或如何缝合。

所以我希望有一些东西可以让我获得所有不可见的元素

1 个答案:

答案 0 :(得分:1)

jsFiddle:https://jsfiddle.net/CanvasCode/q61hb9yf/1

var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");

var Player = function (xSet, ySet) {
    this.XPos = xSet;
    this.YPos = ySet;
    this.Color = "#0F0";
}

var Background = function (xSet, ySet) {
    this.XPos = xSet;
    this.YPos = ySet;
    this.Sprite = new Image();
    this.Sprite.src = "http://i.stack.imgur.com/hcFJb.png";
}

var player = new Player(343, 343);
var background = new Background(0, 0);

function moveSomething(e) {
    switch (e.keyCode) {
        case 37:
            if (background.XPos < 0) {
            background.XPos += 48;
            }
            else{
                player.XPos -= 48;
            }
            break;
        case 38:
            if (background.YPos < 0) {
                background.YPos += 48;
            } else {
                player.YPos -= 48;
            }
            break;
        case 39:
            if (Math.abs(background.XPos) < (c.width / 2)) {
                background.XPos -= 48;
            } else {
                player.XPos += 48;
            }
            break;
        case 40:
            if (Math.abs(background.YPos) < (c.height / 2)) {
                background.YPos -= 48;
            } else {
                player.YPos += 48;
            }
            break;
    }
}

window.addEventListener("keydown", moveSomething, false);



setInterval(function () {
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, c.width, c.height);
    ctx.drawImage(background.Sprite, background.XPos, background.YPos);
    ctx.fillStyle = player.Color;
    ctx.fillRect(player.XPos, player.YPos, 48, 48);
}, 3)

这会将整个图像绘制到画布上,并允许用户使用箭头键移动,没有碰撞检测。