案例问题..
来源:9-3 完成案例动画部分
qq_林二爷_0
2018-09-13 21:18:06
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>canvas</title>
<style type="text/css">
#canvas1{
background: grey;
position: absolute;
top: 100px;
left: 40px;
}
#canvas2{
background: lightgrey;
position: absolute;
top: 100px;
left: 390px;
}
.inpuBox{
position: absolute;
top: 120px;
left: 90px;
}
input{
width: 250px;
height: 25px;
border: none;
border-radius: 20px;
text-indent: 1em;
font-size: 12px;
font-family: "微软雅黑";
margin-bottom: 10px;
outline: none;
}
#btn{
font-family: "微软雅黑";
font-size: 12px;
width: 100px;
height: 25px;
line-height: 25px;
background-color: black;
color: white;
border: none;
border-radius: 20px;
margin-left: 75px;
outline: none;
}
</style>
</head>
<body>
<canvas id="canvas1" width="350" height="350">
该浏览器不支持canvas
</canvas>
<canvas id="canvas2" width="800" height="350">
该浏览器不支持canvas
</canvas>
<div class="inpuBox">
<p><input type="text" placeholder="姓名" /></p>
<p><input type="text" placeholder="地址" /></p>
<p><input type="text" placeholder="职业" /></p>
<p><input type="text" placeholder="口号" /></p>
<p><button id="btn">生成名片</button></p>
</div>
<script type="text/javascript">
var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas2=document.getElementById("canvas2");
var ctx2=canvas2.getContext("2d");
ctx2.save();
//添加渐变
var linearGradient=ctx2.createLinearGradient(450,150,1000,300);
linearGradient.addColorStop(0,"black");
linearGradient.addColorStop(1,"white");
ctx2.fillStyle=linearGradient;
//添加矩形框
ctx2.fillRect(100,100,600,100);
ctx2.restore();
//添加图片
ctx2.save();
ctx2.arc(150,150,45,0,Math.PI*2);
ctx2.clip();
var img=new Image();
img.src="img/111.png";
img.onload=function(){
ctx2.drawImage(img,100,100,100,100);
}
ctx2.restore();
//添加文字
var name="请输入姓名";
var address="请输入地址";
var job="请输入职业";
var kouhao="请输入口号";
ctx2.font="25px 微软雅黑";
ctx2.fillStyle="white";
ctx2.fillText(name,210,125);
ctx2.font="18px 微软雅黑";
ctx2.fillText(address,211,160);
ctx2.fillText(job,211,190);
ctx2.fillText(kouhao,500,160);
</script>
</body>
</html>为什么我加了第二个ctx2.save()之后,ctx2.clip()没有效果;然后去掉之后就有效果了,但是文字又不见了。
希望老师再详细解释一下save()和restore()这两个方法。
1回答
好帮手慕星星
2018-09-14
save:用来保存Canvas原本的状态。save之后,可以调用Canvas的平移、放缩、旋转、错切、裁剪等操作。
restore:用来恢复Canvas之前保存的状态。防止save后对Canvas执行的操作对后续的绘制有影响。
clip() 方法从原始画布中剪切任意形状和尺寸。
提示:一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内(不能访问画布上的其他区域)。您也可以在使用 clip() 方法前通过使用 save() 方法对当前画布区域进行保存,并在以后的任意时间对其进行恢复(通过 restore() 方法)
如果添加图片在前面的话,保存裁剪之前的状态,裁剪之后再恢复,那么就不是裁剪之后的形状了,所以建议先添加文字,如下:

自己测试下,祝学习愉快~~
相似问题