您的位置:首页 > Web前端 > HTML5

Html5 canvas标签实现简易画图板

2017-07-29 16:43 537 查看
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
.zt {
width: 600px;
height: 600px;
border: solid 4px rgba(0, 0, 0, 0.67);
margin-left: 300px;
}
#canvas {
border-top: solid 1px #000000;
margin-top: 60px;
}
h1 {
margin-left: 500px;
}

input {
margin-left: 30px;
margin-top: 60px;
width: 62px;
height: 30px;
font-size: 14px;
color: white;
}
#qianbi{
background-color: #fff318;
}
#zhixian{
background-color: #ffa558;
}
#juxing{
background-color: #e23cc1;
}
#yuanjiao{
background-color: #4434e2;
}
#yuan{
background-color: #2ce24b;
}
#color{
background-color: #fc041c;
}
</style>

</head>
<body>
<h1>简易画图板</h1><br/>

<div class="zt">
<div id="an">
<input type="button" id="qianbi" value="铅笔" />
<input type="button" id="zhixian" value="直线" />
<input type="button" id="juxing" value="矩形" />
<input type="button" id="yuanjiao" value="圆角矩形" />
<input type="button" id="yuan" value="圆" />
<input type="color"  id="color" value="颜色"/>
</div>
<canvas id="canvas" width="600" height="550">

你的浏览器不支持canvas标签,请使用firefox和chrome浏览器

</canvas>
</div>

<script type="text/javascript">
var x1;
var y1;
var x2;
var y2;
var index = 0;
var kg = false;
//    var  ys=document.getElementById("color")
//    console.log("ys");
var cv = document.getElementById("canvas");
var zx = cv.getContext("2d");
//获取上面div的INPUT
var anniu = document.getElementById("an").getElementsByTagName("input");
for (var i = 0; i < anniu.length; i++) {
anniu[i].index = i;
anniu[i].onclick = function () {
index = this.index;
console.log(index);
}
}

cv.onmousedown = function (event) {
var e = event || window.event;
x1 = e.offsetX;
y1 = e.offsetY;
console.log("x1=" + x1 + "  y=" + y1);
if (index == 0) {
kg = true;
cv.onmousemove = function (event) {
if (kg == true) {
var e = event || window.event;
var x3 = e.offsetX;
var y3 = e.offsetY;
zhixian(x1, y1, x3, y3);
x1 = x3;
y1 = y3;
}
}
};
};
cv.onmouseup = function (event) {
var e = event || window.event;
x2 = e.offsetX;
y2 = e.offsetY;
console.log("x2=" + x2 + "  y2=" + y2);
kg = false;
if (index == 1) {
zhixian(x1, y1, x2, y2);
} else if (index == 2) {
juxing(x1, y1, x2, y2);
} else if (index == 3) {
yuanjiao(x1, y1, x2 - x1, y2 - y1);
}else if(index ==4){
yuan(x1, y1, x2 - x1, y2 - y1);
}
};
cv.onmouseout = function () {
kg = false;
};

//画直线
function zhixian(x1, y1, x2, y2) {
zx.beginPath();
zx.moveTo(x1, y1);
zx.lineTo(x2, y2);
zx.stroke();
}
//    画矩形
function juxing(x1, y1, x2, y2) {
zx.rect(x1, y1, x2 - x1, y2 - y1);
zx.stroke();
}

//    圆角矩形
function yuanjiao(x, y, w, h) {

}
//画圆
function yuan(x1, y1, x2, y2){
zx.beginPath();
var r=(x1-x2)/2
console.log(r,x2,x1);
zx.arc(x1,y1,r,0,2*Math.PI);
zx.closePath();
zx.stroke();
}
</script>
</body>
</html>
效果图如下。矩形效果未实现

简易画图板

你的浏览器不支持canvas标签,请使用firefox和chrome浏览器
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息