如何画一条可以用画布向左移动的曲线? [英] How to draw a curve that could move to left with canvas?
问题描述
我正在编写一个程序,用画布绘制正弦曲线
。
HTML:
I'm writing a program that will draw the sine curve
with canvas.
HTML:
<canvas id="mycanvas" width="1000" height="100">
Your browser is not supported.
</canvas>
JavaScript:
JavaScript:
var canvas = document.getElementById("mycanvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.lineWidth = 3;
var x = 0,
y = 0;
var timeout = setInterval(function() {
ctx.beginPath();
ctx.moveTo(x, y);
x += 1;
y = 50 * Math.sin(0.1 * x) + 50;
ctx.lineTo(x, y);
ctx.stroke();
if (x > 1000) {
clearInterval(timeout);
}
}, 10);
}
这非常好用: http://jsfiddle.net/HhGnb/
但是,现在我只能说100px画布宽度,因此只能看到曲线的最低100px。 http://jsfiddle.net/veEyM/1/
我想要归档这种效果:当曲线的右边点大于画布的宽度时,整条曲线可以向左移动,所以我可以看到曲线最右边的点,有点像曲线向左流动。我可以这样做吗?
However, now I can only offer say 100px for the canvas width, so only the leftest 100px of the curve could be seen. http://jsfiddle.net/veEyM/1/
I want to archive this effect: when the right point of the curve is bigger than the width of canvas, the whole curve could move left, so I can see the rightest point of the curve, it's a bit like the curve is flowing to left. Can I do that?
推荐答案
< canvas> $的基本构思之一c $ c>元素是计算机忘记绘图命令并仅保存像素,如位图。因此,要将所有内容移到左侧,您需要清除画布并再次绘制所有内容。
One of the basic ideas of the <canvas>
element is that the computer 'forgets' the drawing commands and only saves the pixels, like a bitmap. So to move everything to the left, you need to clear the canvas and draw everything again.
还有一件事我想建议你 - 你总是要开始在x = 0且y = 0的情况下,但显然在x = 0时,y也不一定等于0。编辑:实现了这个。
There is also one thing I'd like to advise you - you always start with x = 0 and y = 0, but obviously at x = 0 then y is not necessarily equal to 0 as well. implemented this.
无论如何,我最终得到了这段代码: http://jsfiddle.net/veEyM/5/
Anyway, I ended up with this code: http://jsfiddle.net/veEyM/5/
var canvas = document.getElementById("mycanvas");
var points = {}; // Keep track of the points in an object with key = x, value = y
var counter = 0; // Keep track when the moving code should start
function f(x) {
return 50 * Math.sin(0.1 * x) + 50;
}
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.lineWidth = 3;
var x = 0,
y = f(0);
var timeout = setInterval(function() {
if(counter < 100) { // If it doesn't need to move, draw like you already do
ctx.beginPath();
ctx.moveTo(x, y);
points[x] = y;
x += 1;
y = f(x);
ctx.lineTo(x, y);
ctx.stroke();
if (x > 1000) {
clearInterval(timeout);
}
} else { // The moving part...
ctx.clearRect(0, 0, 100, 100); // Clear the canvas
ctx.beginPath();
points[x] = y;
x += 1;
y = f(x);
for(var i = 0; i < 100; i++) {
// Draw all lines through points, starting at x = i + ( counter - 100 )
// to x = counter. Note that the x in the canvas is just i here, ranging
// from 0 to 100
ctx.lineTo(i, points[i + counter - 100]);
}
ctx.stroke();
}
counter++;
}, 10);
}
这篇关于如何画一条可以用画布向左移动的曲线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!