Javascript 如何重置画布路径样式?
我有创建函数来绘制画布形状和线条,如休闲代码:Javascript 如何重置画布路径样式?,javascript,canvas,Javascript,Canvas,我有创建函数来绘制画布形状和线条,如休闲代码: function drawBaseline(ctx, lineLeft, lineTop, lineEndLeft, strockWidth, strockColor) { ctx.beginPath(); ctx.lineWidth = strockWidth; ctx.strokeStyle = strockColor; ctx.moveTo(lineLeft, lin
function drawBaseline(ctx, lineLeft, lineTop, lineEndLeft, strockWidth, strockColor) {
ctx.beginPath();
ctx.lineWidth = strockWidth;
ctx.strokeStyle = strockColor;
ctx.moveTo(lineLeft, lineTop);
ctx.lineTo(lineEndLeft, lineTop);
ctx.stroke();
}
function drawDashedLine(ctx, lineLeft, lineTop, lineEndLeft, strockWidth, strockColor, lineDash) {
ctx.beginPath();
ctx.setLineDash(lineDash);
ctx.lineCap = 'round';
ctx.moveTo(lineLeft, lineTop);
ctx.lineWidth = strockWidth;
ctx.strokeStyle = strockColor;
ctx.lineTo(lineEndLeft, lineTop);
ctx.stroke();
}
但是当我在drawDashedLine
之后调用drablesline
时,也是在画虚线
drawDashedLine(ctx, 0, lineTop, 300, 5, 'red', [5, 20]);
drawBaseline(ctx, 0, lineTop, canvas.width, 1, 'black');
如何重置上下文重置以绘制新对象?缓慢但懒惰的方法是在设置路径样式之前调用,然后在设置完成后调用 但这将保存您上下文的所有属性,可能还有很多您没有触及的属性(
fillStyle
,strokeStyle
,变换矩阵,剪裁区域,globalAlpha
,gCO,dashOffset,lineCap,font,text align…:所有这些属性都此外,如果出于任何原因,在执行
save()
之后忘记调用restore()
,则保存的状态将累积到内存中,这是不好的
功能牵引杆基线(ctx、lineLeft、lineTop、lineEndLeft、strockWidth、strockColor){
ctx.save();
ctx.beginPath();
ctx.lineWidth=strockWidth;
ctx.strokeStyle=strockColor;
ctx.moveTo(线路左侧、线路顶部);
ctx.lineTo(lineEndLeft,lineTop);
ctx.stroke();
//现在恢复所有属性
ctx.restore();
}
函数drawDashedLine(ctx、lineLeft、lineTop、lineEndLeft、strockWidth、strockColor、lineDash){
ctx.save();
ctx.beginPath();
ctx.setLineDash(lineDash);
ctx.lineCap='圆形';
ctx.moveTo(线路左侧、线路顶部);
ctx.lineWidth=strockWidth;
ctx.strokeStyle=strockColor;
ctx.lineTo(lineEndLeft,lineTop);
ctx.stroke();
//现在恢复所有属性
ctx.restore();
}
var ctx=canvas.getContext('2d');
var-lineTop=100;
drawDashedLine(ctx,0,lineTop,300,5,'红色',[5,20]);
牵引杆线(ctx,0,线顶,画布宽度,1,'黑色')代码>
缓慢但懒惰的方法是在设置路径样式之前调用,然后在设置完成后调用
但这将保存您上下文的所有属性,可能还有很多您没有触及的属性(fillStyle
,strokeStyle
,变换矩阵,剪裁区域,globalAlpha
,gCO,dashOffset,lineCap,font,text align…:所有这些属性都
此外,如果出于任何原因,在执行save()
之后忘记调用restore()
,则保存的状态将累积到内存中,这是不好的
功能牵引杆基线(ctx、lineLeft、lineTop、lineEndLeft、strockWidth、strockColor){
ctx.save();
ctx.beginPath();
ctx.lineWidth=strockWidth;
ctx.strokeStyle=strockColor;
ctx.moveTo(线路左侧、线路顶部);
ctx.lineTo(lineEndLeft,lineTop);
ctx.stroke();
//现在恢复所有属性
ctx.restore();
}
函数drawDashedLine(ctx、lineLeft、lineTop、lineEndLeft、strockWidth、strockColor、lineDash){
ctx.save();
ctx.beginPath();
ctx.setLineDash(lineDash);
ctx.lineCap='圆形';
ctx.moveTo(线路左侧、线路顶部);
ctx.lineWidth=strockWidth;
ctx.strokeStyle=strockColor;
ctx.lineTo(lineEndLeft,lineTop);
ctx.stroke();
//现在恢复所有属性
ctx.restore();
}
var ctx=canvas.getContext('2d');
var-lineTop=100;
drawDashedLine(ctx,0,lineTop,300,5,'红色',[5,20]);
牵引杆线(ctx,0,线顶,画布宽度,1,'黑色')代码>