ale*_*lex 3 javascript interpolation canvas
我有一个适用于触摸事件的绘画风格的应用程序.

JavaScript代码是......
var RADIUS = 10;
var ctx = document.querySelector("canvas").getContext("2d");
var getRandomColorFragment = function () {
return Math.floor(Math.random() * 255);
};
document.body.addEventListener("touchstart", function (event) {
ctx.fillStyle = "rgb(" + [getRandomColorFragment(), getRandomColorFragment(), getRandomColorFragment()].join() + ")";
});
document.body.addEventListener("touchmove", function (event) {
// Prevent default behavior of scrolling elements.
event.preventDefault();
// Get a reference to the first touch placed.
var touch = event.touches[0];
// Draw a circle at the location of the finger.
ctx.beginPath();
ctx.arc(touch.pageX - RADIUS, touch.pageY - RADIUS, RADIUS, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
});
Run Code Online (Sandbox Code Playgroud)
您可以使用Chrome并打开Web Inspector的设置并选择" 模拟触摸事件",在不支持触摸事件的平台上对此进行测试.
当手指/指针移动得非常快时,它无法像预期的那样不断地绘制画布(见上面的截图).似乎我只能在touchmove事件触发时获得触摸的坐标.
我认为我可以使用距离公式(c2 = a2 + b2)确定弧之间是否有足够大的间隙,并确定它是否大于RADIUS常数.这部分运作良好.我需要弄清楚的另一件事是如何在两点之间进行插值:先前注册的触摸坐标和新注册的坐标.
所以,基本上,我想知道如何在两点之间进行插值,以确定如何填补空白.
您想从最后一个鼠标位置到新鼠标位置绘制一条线.但是你正在新的位置画一个圆圈.为什么?
你为什么不这样做?
onTouchStart: ctx.moveTo(x,y);
onTouchMove: ctx.lineTo(x,y);
Run Code Online (Sandbox Code Playgroud)
所有插值,抗锯齿等都已包含在"lineTo"功能中.使用 ctx.lineCap = "round";有圆角.
如果您仍想插入数字,这里是函数:
function interpolate(a, b, frac) // points A and B, frac between 0 and 1
{
var nx = a.x+(b.x-a.x)*frac;
var ny = a.y+(b.y-a.y)*frac;
return {x:nx, y:ny};
}
interpolate({x:2, y:2}, {x:4,y:4}, 0.5); // returns {x:3, y:3}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3956 次 |
| 最近记录: |