<!DOCTYPE html>
<html>
<head>
<title>canvas</title>
<meta charset="utf-8" >
<script src="js/jquery.js"></script>
</head>
<body>
<div>
<canvas id="canvas" width="1000px;" height="500px" style="background:green;border:1px solid #fff;"></canvas><br/>
<button class="clear" style="cursor:pointer;margin-top:10px;margin-left:10px;width:150px;height:100px;font-size:40px;">清除</button>
<button class="save" style="cursor:pointer;margin-top:10px;margin-left:10px;width:180px;height:100px;font-size:40px;">保存图片</button>
<div class="img"><img src=""></div>
</div>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.lineWidth = '5';
var bbox = c.getBoundingClientRect();
// ctx.moveTo(0, 0);
// ctx.lineTo(290, 140);
// ctx.stroke();
var state = '';
$(".clear").click(function () {
ctx.beginPath();
ctx.clearRect(0, 0, 1000, 500);
})
function browserRedirect() {
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
var bIsMidp = sUserAgent.match(/midp/i) == "midp";
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
var bIsAndroid = sUserAgent.match(/android/i) == "android";
var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
$("body").on("touchstart", "#canvas", function (e) {
})
$("body").on("touchmove", "#canvas", function (e) {
e.preventDefault();
var _touch = e.originalEvent.targetTouches[0];
var x = _touch.clientX - bbox.left * (c.width / bbox.width);
var y = _touch.clientY - bbox.top * (c.height / bbox.height);
if (!state) {
ctx.moveTo(x, y);
state = '1';
}
ctx.lineTo(x + 1, y + 1);
ctx.strokeStyle = '#AACDEE';
ctx.stroke();
})
$("body").on("touchend", "#canvas", function (e) {
state = '';
})
} else {
var state = '';
$("body").on("mousedown", "#canvas", function () {
$("body").on("mousemove", "#canvas", function (e) {
var x = e.clientX - bbox.left * (c.width / bbox.width);
var y = e.clientY - bbox.top * (c.height / bbox.height);
if (!state) {
ctx.moveTo(x, y);
state = '1';
}
ctx.lineTo(x + 1, y + 1);
ctx.strokeStyle = '#AACDEE';
ctx.stroke();
console.log(x, y);
})
})
$("body").on("mouseup", "#canvas", function () {
state = '';
$("body").off("mousemove", "#canvas");
})
}
}
browserRedirect();
$(".save").click(function () {
var img = c.toDataURL();
$(".img img").attr("src", img);
})
</script>
</body>
</html>