Javascript 如何向负x轴水平平移画布

Javascript 如何向负x轴水平平移画布,javascript,html,canvas,Javascript,Html,Canvas,我正在尝试用canvas实现正弦波演示。我能用动画画正弦波。但我的问题是,当正弦波动画超出画布的视口时,我想将画布向左移动。这是我的密码 <canvas id='a' width="320" height="480"></canvas> 演示: 下面是一种基于X坐标绘制正弦波的有效方法: ctx.fillRect(x,Math.sin(x/10)*30+50,1,1); 直到波浪到达画布的末端,才正常绘制波浪 当波浪到达画布的末端时,可以重新绘制整个波浪,但向左移动1

我正在尝试用canvas实现正弦波演示。我能用动画画正弦波。但我的问题是,当正弦波动画超出画布的视口时,我想将画布向左移动。这是我的密码

<canvas id='a' width="320" height="480"></canvas>
演示:

下面是一种基于X坐标绘制正弦波的有效方法:

ctx.fillRect(x,Math.sin(x/10)*30+50,1,1);
直到波浪到达画布的末端,才正常绘制波浪

当波浪到达画布的末端时,可以重新绘制整个波浪,但向左移动1个像素

// start panning when x reaches panAtX

var n1=x-panAtX;

// set up a temporary xx that draws the wave from -1 to the panAtX position

var xx=-1;

// clear the canvas

ctx.clearRect(0,0,canvas.width,canvas.height);

// redraw the wave, but shifted 1 pixel to the left

for(n=n1;n<x;n++){
    ctx.fillRect(xx++,Math.sin(n/10)*30+50,1,1);
}
//当x到达panAtX时开始平移
var n1=x-panAtX;
//设置一个临时xx,将波浪从-1拉至panAtX位置
var-xx=-1;
//清理画布
clearRect(0,0,canvas.width,canvas.height);
//重新绘制波浪,但向左移动1个像素

因为(n=n1;nMaybe可以帮忙。谢谢Anto,但是MarkE给了我我所需要的东西..宾果!!!这正是我想要的。非常感谢老兄。如果你在附近的话,我会给你买杯啤酒…;)))如果你能告诉我在哪里可以得到canvas的基于三角函数的教程,那就太好了。好消息……所有的三角函数都已经内置到javascripts的“Math”方法中了。这意味着不存在适用于html画布的“特殊”触发器。因此,您找到的任何trig教程(如youTube)都将直接应用于html画布。干杯
// start panning when x reaches panAtX

var n1=x-panAtX;

// set up a temporary xx that draws the wave from -1 to the panAtX position

var xx=-1;

// clear the canvas

ctx.clearRect(0,0,canvas.width,canvas.height);

// redraw the wave, but shifted 1 pixel to the left

for(n=n1;n<x;n++){
    ctx.fillRect(xx++,Math.sin(n/10)*30+50,1,1);
}
var x=0;
var panAtX=250;
var continueAnimation=true;
animate();


function animate(){

    if(continueAnimation){
        requestAnimationFrame(animate);
    }

    if(x++<panAtX){
        ctx.fillRect(x,Math.sin(x/10)*30+50,1,1);
    }else{
        var n1=x-panAtX;
        var xx=-1;

        ctx.clearRect(0,0,canvas.width,canvas.height);
        for(n=n1;n<x;n++){
            ctx.fillRect(xx++,Math.sin(n/10)*30+50,1,1);
        }
    }
}