<script>
let canvasbox = document.getElementById("canvasbox");
let ctx = canvasbox.getContext("2d");
let iscanvas = false;
let offsetX = '';
let offsetY = '';
// 后期替换监听触摸:touchstart
canvasbox.addEventListener("mousedown", function(e){
iscanvas = true;
offsetX = e.offsetX;
offsetY = e.offsetY;
})
// 后期替换监听触摸滑动:touchmove
canvasbox.addEventListener("mousemove", function(e){
if(iscanvas){
ctx.beginPath();
ctx.moveTo(offsetX,offsetY)
ctx.lineTo(e.offsetX,e.offsetY)
ctx.lineWidth = 2;
ctx.stroke()
offsetX = e.offsetX;
offsetY = e.offsetY;
}
})
// 后期替换监听触摸等功能 无替代可能用不到
canvasbox.addEventListener("mouseup", function(){
iscanvas = false;
})
// 后期替换监听触摸离开:touchend
canvasbox.addEventListener("mouseleave", function(){
iscanvas = false;
})
// 清除按钮功能
let clearbtn = document.getElementById("clearbtn");
clearbtn.addEventListener("click",function(){
ctx.clearRect(0,0,canvasbox.width,canvasbox.height)
})
// 保存按钮功能
let savebtn = document.getElementById("savebtn");
savebtn.addEventListener("click",function(){
// 这里做保存的相关操作
})
// 保存成png格式的图片
function saveAsPNG(canvas) {
return canvas.toDataURL("image/png");
}
</script>