我正在尝试用画布创建一个绘图区域。我在绘制曲线时无法使线条看起来平滑,而且我的算法中的线条粗细也发生了变化,这看起来也很糟糕,因为尺寸也跳得很大,你可以看到尺寸变化的地方。我确实在 stackoverflow 上找到了此链接,但这是针对本机 iPhone 应用程序的,我无法弄清楚。
这是我当前的 JS 代码。这是它在 jsFiddle 上运行的
var xStart,
xEnd,
yStart,
yEnd,
paint,
ctx;
$(document).ready(function (){
ctx = $('canvas')[0].getContext("2d");
ctx.strokeStyle = '#000';
ctx.lineJoin="round";
ctx.lineCap="round";
ctx.lineWidth = 1;
$('canvas').bind('mousedown mousemove mouseup mouseleave touchstart touchmove touchend', function(e){
var orig = e.originalEvent;
if(e.type == 'mousedown'){
e.preventDefault(); e.stopPropagation();
xStart = e.clientX - $(this).offset().left;
yStart = e.clientY - $(this).offset().top;
xEnd = xStart;
yEnd = yStart;
paint = true;
draw(e.type);
}else if(e.type == 'mousemove'){
if(paint==true){
xEnd = e.clientX - $(this).offset().left;
yEnd = e.clientY - $(this).offset().top;
lineThickness = 1 + Math.sqrt((xStart - xEnd) *(xStart-xEnd) + (yStart - yEnd) * (yStart-yEnd))/5;
if(lineThickness > 10){
lineThickness = 10;
}
ctx.lineWidth = lineThickness;
draw(e.type);
}
}else if(e.type == 'mouseup'){
paint = false;
}else if(e.type == 'mouseleave'){
paint = false;
}else if(e.type == 'touchstart'){
if(orig.touches.length == 1){
e.preventDefault(); e.stopPropagation();
xStart = orig.changedTouches[0].pageX - $(this).offset().left;
yStart = orig.changedTouches[0].pageY - $(this).offset().top;
xEnd = xStart;
yEnd = yStart;
paint = true;
draw(e.type);
}
}else if(e.type == 'touchmove'){
if(orig.touches.length == 1){
if(paint==true){
xEnd = orig.changedTouches[0].pageX - $(this).offset().left;
yEnd = orig.changedTouches[0].pageY - $(this).offset().top;
lineThickness = 1 + Math.sqrt((xStart - xEnd) *(xStart-xEnd) + (yStart - yEnd) * (yStart-yEnd))/6;
if(lineThickness > 10){
lineThickness = 10;
}
ctx.lineWidth = lineThickness;
draw(e.type);
}
}
}else if(e.type == 'touchend'){
paint = false;
}
});
});
function draw(event){
if(event == 'mousedown'){
ctx.beginPath();
ctx.moveTo(xStart, yStart);
ctx.lineTo(xEnd, yEnd);
ctx.stroke();
}else if(event == 'mousemove'){
ctx.beginPath();
ctx.moveTo(xStart, yStart);
ctx.lineTo(xEnd, yEnd);
ctx.stroke();
}else if(event == 'touchstart'){
ctx.beginPath();
ctx.moveTo(xStart, yStart);
ctx.lineTo(xEnd, yEnd);
ctx.stroke();
}else if(event == 'touchmove'){
ctx.beginPath();
ctx.moveTo(xStart, yStart);
ctx.lineTo(xEnd, yEnd);
ctx.stroke();
}
xStart = xEnd;
yStart = yEnd;
}
谢谢大家。
如果你画画,这就是它现在的样子。
...这就是我想要实现的目标: