学习html5 canvas,写了一个小练习来加深理解,可以实现图形随拖动而复制。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demoCanvas2</title>
<style>
*{margin:0px;padding:0px;} #out{
position:absolute;
width:800px;
height:500px;
position:absolute;
top:0px;
left:0px;
border:1px solid #ff0000;
} .demo1{
position:absolute;
width:100px;
height:100px;
top:10px;
left:10px;
border:1px solid #ff0000;
} #util{
position:absolute;
width:350px;
height:300px;
top:50px;
right:50px;
}
</style>
</head> <body>
<div id="out">
<canvas id="demo1" class="demo1"></canvas>
</div> <div id="util">
<p>
<h2>操作简介</h2>
移动图形:单击图形不放并移动。<br/>
复制图形:松开鼠标。<br/>
结束操作:双击鼠标。 </p>
鼠标横坐标:<input type="text" id="lan1"/><br>
鼠标纵坐标:<input type="text" id="lan2"/>
</div> <script>
//绘制基本图像
var demo1=document.getElementById("demo1");
var pen1=demo1.getContext("2d");
pen1.moveTo(2,2);
pen1.lineTo(20,100);
pen1.lineTo(200,40);
pen1.lineTo(2,2);
pen1.stroke(); //鼠标单击demo1对象时
demo1.onmousedown=function(e){
// 记录demo1的宽和高
var myWidth=e.clientX-demo1.offsetLeft;
var myHeight=e.clientY-demo1.offsetTop; //记录此时坐标位置
var left0=this.offsetLeft;
var top0=this.offsetTop; //鼠标移动时
demo1.onmousemove=function(e){
//demo1跟随鼠标坐标
demo1.style.left=e.clientX-myWidth+"px";
demo1.style.top=e.clientY-myHeight+"px"; //设置边界,当对象移动到右边界,左边距始终保持700px
if(demo1.offsetLeft>=700){
demo1.style.left=700+"px";
}
// 当对象移动到左边界,左边距始终为0px
if(demo1.offsetLeft<=0){
demo1.style.left=0+"px";
}
//当对象移动到下边界,上边距始终为400px
if(demo1.offsetTop>=400){
demo1.style.top=400+"px"; }
//当对象移动到上边界,上边距始终为0px
if(demo1.offsetTop<=0){
demo1.style.top=0+"px";
}
//显示鼠标坐标位置
var lan1=document.getElementById("lan1");
var lan2=document.getElementById("lan2");
lan1.value=e.clientX;
lan2.value=e.clientY; } //当鼠标松开时
demo1.onmouseup=function(){ //创建新标签<canvas>
var demo=document.createElement("canvas");
//动态设置<canvas>对象的样式
demo.style.cssText="width:100px;height:100px;position:absolute;left:"+left0+"px;"+"top:"+top0+"px;border:1px solid #ff0000";
//将对象加入到body中
var body=document.getElementsByTagName("body")[0];
body.appendChild(demo); var pen=demo.getContext("2d");
pen1.moveTo(2,2);
pen.lineTo(20,100);
pen.lineTo(200,40);
pen.lineTo(2,2);
pen.stroke();
} //双击鼠标时结束
window.ondblclick=function(){
alert("执行结束!");
}
}
</script> <div id="test"></div>
</body>
</html>
如果您觉得我写的东西对您有些帮助,请帮我点个推荐,互粉交个学习路上的好友,我是菜鸟,你的鼓励是我前进的动力。