第一:quadraticCurveTo绘图产生空隙
let points=[];
let beginPoint =null;
//鼠标点击
canvas.mousedown(function (ev) {
ev = ev || window.event;
const { x, y } = _this.getPos(ev);
points.push({ x, y });
beginPoint = { x, y }
_this.bool = true;
})
//鼠标移动
canvas.mousemove(function (ev) {
if (!_this.bool) {
return
}
const { x, y } = _this.getPos(ev);
points.push({ x, y });
if (points.length > 3) {
const lastTwoPoints =points.slice(-2);
const controlPoint = lastTwoPoints[0];
const endPoint = { x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2, y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2 }
_this.drawLine(beginPoint, controlPoint, endPoint);
beginPoint = endPoint;
}
//鼠标松开
canvas.mouseup(function (ev) {
const { x, y } = _this.getPos(ev);
points.push({ x, y });
if (points.length > 3) {
const lastTwoPoints = points.slice(-2);
const controlPoint = lastTwoPoints[0];
const endPoint = lastTwoPoints[1];
_this.drawLine(beginPoint, controlPoint, endPoint);
}
_this.bool = false;
points = [];
})
//画图函数
drawLine: function (beginPoint, controlPoint, endPoint) {
let _this = this;
_this.ctx.beginPath();
_this.ctx.moveTo(beginPoint.x, beginPoint.y);
_this.ctx.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
_this.ctx.stroke();
_this.ctx.closePath();
},
使用过lineto绘制,虽然无空隙的问题,但是锯齿更加严重
无空隙,锯齿相对能圆滑些(不求完全消除)
分辨率处理逻辑在
https://github.com/doodlewind...
以及
https://github.com/doodlewind...
这个chart.js的源码
let width = canvas.width,height=canvas.height;
if (window.devicePixelRatio) {
canvas.style.width = width + "px";
canvas.style.height = height + "px";
canvas.height = height * window.devicePixelRatio;
canvas.width = width * window.devicePixelRatio;
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
}
来解决canvas锯齿问题。