首页
IT
登录
6mi
u
盘
搜
搜 索
IT
canvas中的状态保存与恢复
canvas中的状态保存与恢复
xiaoxiao
2021-03-25
97
保存的方法save(),恢复的方法restore()
保存方法,是将状态保存在一个状态栈里,先进后出,后进先出
。
示例demo:
<
script
>
var
canvas =
document
.
getElementById
(
"canvas"
);
var
ctx = canvas
.
getContext
(
"2d"
);
//1
、绘制一个绿色描边的矩形
ctx
.
strokeStyle
=
"green"
;
ctx
.
lineWidth
=
3
;
ctx
.
setLineDash
([
10
,
5
,
2
,
5
]);
ctx
.
strokeRect
(
50
,
50
,
300
,
200
);
//2
、绘制一个红色描边的圆
ctx
.
beginPath
();
ctx
.
lineWidth
=
5
;
ctx
.
strokeStyle
=
"red"
;
ctx
.
setLineDash
([]);
ctx
.
arc
(
600
,
150
,
150
,
0
,
2
*
Math
.
PI
);
ctx
.
stroke
();
//3
、绘制一个绿色描边的圆
ctx
.
beginPath
();
ctx
.
setLineDash
([
10
,
5
,
2
,
5
]);
ctx
.
lineWidth
=
3
;
ctx
.
strokeStyle
=
"green"
;
ctx
.
arc
(
500
,
400
,
150
,
0
,
2
*
Math
.
PI
);
ctx
.
stroke
();
</
script
>
运用保存和恢复的写法:
<
script
>
var
canvas =
document
.
getElementById
(
"canvas"
);
var
ctx = canvas
.
getContext
(
"2d"
);
//1
、绘制一个绿色描边的矩形
ctx
.
strokeStyle
=
"green"
;
ctx
.
lineWidth
=
3
;
ctx
.
setLineDash
([
10
,
5
,
2
,
5
]);
ctx
.
strokeRect
(
50
,
50
,
300
,
200
);
ctx
.
save
();
//2
、绘制一个红色描边的圆
ctx
.
beginPath
();
ctx
.
lineWidth
=
5
;
ctx
.
strokeStyle
=
"red"
;
ctx
.
setLineDash
([]);
ctx
.
arc
(
600
,
150
,
150
,
0
,
2
*
Math
.
PI
);
ctx
.
stroke
();
//3
、绘制一个绿色描边的圆
ctx
.
beginPath
();
//
恢复
ctx
.
restore
();
ctx
.
arc
(
500
,
400
,
150
,
0
,
2
*
Math
.
PI
);
ctx
.
stroke
();
</
script
>
save保存的状态栈的原理:先进后出:
<
script
>
var
canvas =
document
.
getElementById
(
"canvas"
);
var
ctx = canvas
.
getContext
(
"2d"
);
//1
、绘制一个绿色描边的矩形
ctx
.
strokeStyle
=
"green"
;
ctx
.
lineWidth
=
3
;
ctx
.
setLineDash
([
10
,
5
,
2
,
5
]);
ctx
.
strokeRect
(
50
,
50
,
300
,
200
);
ctx
.
save
();
//2
、绘制一个红色描边的圆
ctx
.
beginPath
();
ctx
.
lineWidth
=
5
;
ctx
.
strokeStyle
=
"red"
;
ctx
.
setLineDash
([]);
ctx
.
arc
(
600
,
150
,
150
,
0
,
2
*
Math
.
PI
);
ctx
.
stroke
();
ctx
.
save
();
//3
、绘制一个绿色描边的圆
ctx
.
beginPath
();
//
恢复
ctx
.
restore
();
//
恢复到第二个状态
ctx
.
restore
();
//
恢复到第一个状态
ctx
.
arc
(
500
,
400
,
150
,
0
,
2
*
Math
.
PI
);
ctx
.
stroke
();
</
script
>
保存和恢复方法使用的示例
demo1
<
script
>
var
canvas =
document
.
getElementById
(
"canvas"
);
var
ctx = canvas
.
getContext
(
"2d"
);
ctx
.
strokeRect
(
0
,
0
,
300
,
200
);
ctx
.
save
();
ctx
.
translate
(
200
,
200
);
ctx
.
strokeRect
(
0
,
0
,
300
,
200
);
ctx
.
restore
();
ctx
.
clearRect
(
0
,
0
,
canvas
.
width
,
canvas
.
height
);
</
script
>
demo2:
<
script
>
var
canvas =
document
.
getElementById
(
"canvas"
);
var
ctx = canvas
.
getContext
(
"2d"
);
var
x=
0
;
var
timer=
setInterval
(
function
(){
ctx
.
clearRect
(
0
,
0
,
canvas
.
width
,
canvas
.
height
);
ctx
.
save
();
ctx
.
translate
(
x
,
0
);
ctx
.
strokeRect
(
0
,
0
,
300
,
200
);
ctx
.
restore
();
x++
;
},
10
);
</
script
>
。
转载请注明原文地址: https://ju.6miu.com/read-25246.html
技术
最新回复
(
0
)