sdwsq
2016-12-15 13:49
为什么手机端都是1像素粗细呢
var cw = Math.min(800,$(window).width()-20);
var ch = cw;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var inmove=false;
var lastLoc={x:0,y:0}
var lastlinewidth=-1;
var lastTime=0;
canvas.width = cw;
canvas.height = ch;
drawback();
//鼠标和canvas互动的必要函数
function windowto(x,y){
var boxx=canvas.getBoundingClientRect()
return {x:Math.round(x-boxx.left), y:Math.round(y-boxx.top)}
}
$("#clear").click(function(){
ctx.clearRect(0,0,cw,ch)
drawback();
})
function begin(point){
inmove=true;
lastLoc=windowto(point.x,point.y)
lastTime=new Date().getTime();
}
function end(){
inmove=false
}
canvas.onmousedown=function(e){
e.preventDefault()
begin({x:e.clientX,y:e.clientY})
}
canvas.onmouseup=function(e){
e.preventDefault()
end()
}
canvas.onmouseout=function(e){
e.preventDefault()
end()
}
canvas.onmousemove=function(e){
e.preventDefault()
if(inmove){
move({x:e.clientX,y:e.clientY})
}
}
canvas.addEventListener('touchstart',function(e){
e.preventDefault()
touch=e.touches[0]
begin({x:touch.pageX,Y:touch.pageY})
})
canvas.addEventListener('touchmove',function(e){
e.preventDefault()
if(inmove){
touch=e.touches[0]
move({x:touch.pageX , y:touch.pageY})
}
})
canvas.addEventListener('touchend',function(e){
e.preventDefault()
end()
})
function calelinewidth(t,s){
var v=s/t;
var resultLinewidth;
if(v<=0.1)
resultLinewidth=30
else if(v>=10)
resultLinewidth=1
else
resultLinewidth=30-(v-0.1)/(10-0.1)*(30-1)
if(lastlinewidth==-1)
return resultLinewidth
return lastlinewidth*2/3+resultLinewidth*1/3
}
function move(point){
var curLoc=windowto(point.x,point.y)
var curtime=new Date().getTime()
var s=calc(lastLoc,curLoc)
var t=curtime-lastTime;
var linewidth=calelinewidth(t,s);
ctx.beginPath()
ctx.moveTo(lastLoc.x,lastLoc.y)
ctx.lineTo(curLoc.x,curLoc.y)
ctx.strokeStyle="black"
ctx.lineWidth=linewidth
ctx.lineCap="round"
ctx.lineJoin="round"
ctx.stroke();
lastLoc=curLoc;
lastTime=curtime;
lastlinewidth=linewidth;
}
function calc(loc1,loc2){
return Math.sqrt((loc1.x-loc2.x)*(loc1.x-loc2.x)+(loc1.y-loc2.y)*(loc1.y-loc2.y))
}
function drawback() {
ctx.save()
ctx.strokeStyle = "brown"
ctx.beginPath()
ctx.moveTo(3, 3)
ctx.lineTo(cw - 3, 3)
ctx.lineTo(cw - 3, ch - 3)
ctx.lineTo(3, ch - 3)
ctx.closePath()
ctx.lineWidth = 6
ctx.stroke()
ctx.beginPath()
ctx.setLineDash([10, 10]);
ctx.moveTo(0, 0);
ctx.lineTo(cw, ch);
ctx.moveTo(cw, 0);
ctx.lineTo(0, ch);
ctx.moveTo(cw / 2, 0)
ctx.lineTo(cw / 2, ch)
ctx.moveTo(0, ch / 2)
ctx.lineTo(cw, ch / 2)
ctx.lineWidth = 1;
ctx.stroke()
ctx.restore()
}
学写一个字
70879 学习 · 52 问题
相似问题