图片的坐标为什么变了
来源:6-7 完成案例文字图片显示和变换
光aaaaand影
2019-08-17 20:24:12
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="css/style.css"/> </head> <body> <!-- 左边 --> <div class="left-div"> <div class="line"> <input id="name" type="text" placeholder="姓名"/> </div> <div class="line"> <input id="address" type="text" placeholder="地址"/> </div> <div class="line"> <input id="job" type="text" placeholder="职业"/> </div> <div class="line"> <input id="slogan" type="text" placeholder="口号"/> </div> <div class="line"> <button id="createBtn">生成名片</button> </div> </div><!--left-div --> <!-- 右边 --> <div class="right-div"> <canvas id="animCanvas" width="600" height="100"> 您的浏览器不支持Canvas,请升级浏览器 </canvas> </div> <script type="text/javascript" src="js/script.js"></script> </body> </html>
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
.left-div {
width: 30%;
height: 100%;
float: left;
background: #a4a296;
}
.line {
text-align: center;
margin-top: 30px;
}
.line:first-child {
margin-top: 200px;
}
.line span {
color: white;
}
.line input {
width: 300px;
height: 30px;
border-radius: 15px;
padding-left: 15px;
outline: none;
border: none;
}
.line button {
width: 100px;
height: 30px;
outline: none;
border: none;
background: #222;
color: #DDD;
cursor: pointer;
position: relative;
border-radius: 15px;
}
.line button:hover {
background: #000;
color: #FFF;
}
.line button:active {
left: 1px;
top: 1px;
}
.right-div {
width: 70%;
height: 100%;
float: left;
background: #eee9d3;
text-align: center;
position: relative;
}
.right-div canvas {
position: absolute;
top: 200px;
left: 50%;
margin-left: -300px;
}
#cardCanvas {
display: none;
}var canvas=document.getElementById("animCanvas");
var ctx=canvas.getContext("2d");
var name="请输入姓名",
address="请输入地址",
job="请输入职业",
slogan="请输入口号";
//绘制画布的函数
var draw=function(){
//渐变
var lg=ctx.createLinearGradient(0,0,600,100);
lg.addColorStop(0.5,"#000");
lg.addColorStop(1,"rgb(133,133,133)");
ctx.fillStyle=lg;
ctx.fillRect(0,0,600,100);
// 引入logo
var img=new Image();
img.src="img/logo.png";
img.onload=function(){
ctx.drawImage(img,10,10);
}
// 调用绘制文字的函数
text(name,address,job,slogan);
}
//绘制文字的函数
var text=function(str1,str2,str3,str4){
ctx.font= "bold 30px sans-serif";
ctx.fillStyle="#FFF";
ctx.fillText(str1,105,35);
ctx.font= "bold 22px sans-serif";
ctx.fillText(str2,105,60);
ctx.fillText(str3,105,85);
ctx.translate(370,70);
ctx.rotate(-Math.PI/12);
ctx.fillStyle="rgba(255,255,255,0.7)";
ctx.fillText(str4,0,0);
}
// 点击按钮,提交信息
var btn=document.getElementById("createBtn");
btn.onclick=function(){
canvas.height=canvas.height;//清除画布
name=document.getElementById("name").value,
address=document.getElementById("address").value,
job=document.getElementById("job").value;
draw();
}
//第一次绘制
draw();老师,我在“绘制文字的函数”里将str4平移与旋转,为什么图片也跟着平移和旋转了,图片的引入在绘制文字之前,按理说不该受影响啊
1回答
同学你好!
是被影响到了,因为onload事件是在图片加载完之后执行的,可能在旋转之后,所以logo图片就进行了旋转。如果想要口号进行旋转,可以使用save方法保存之前的状态,在绘制口号之前旋转,参考:

效果:

如果帮助到了你,欢迎采纳,祝学习愉快~
相似问题