<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
canvas {
display: block;
}
</style>
</head>
<body>
<canvas width="500" height="400"></canvas>
<div class="wrapper">
<input id="color" type="color" value="#ffffff">
<input id="range" type="range" max="50" min="5">
<button id="brush" type="button">画笔</button>
<button id="rubbish" type="button">垃圾桶</button>
<button id="save" type="button">保存</button>
</div>
<script>
function $(selector) {
return typeof selector === "string" ? document.querySelector(selector) : selector;
};
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, canvas.width, canvas.height);
bindEventFn();
function bindEventFn() {
$("#brush").addEventListener("click", brushFn);
$("#rubbish").addEventListener("click", rubshFn);
$("#save").addEventListener("click", saveFn);
canvas.addEventListener("mousedown", startFn)
};
function brushFn() {
if (this.innerHTML === "画笔") {
this.innerHTML = "橡皮擦";
ctx.globalCompositeOperation = "source-over";
} else {
this.innerHTML = "画笔";
ctx.globalCompositeOperation = "destination-out";
}
}
function saveFn() {
var src = canvas.toDataURL();
var img = new Image();
img.src = src;
img.onload = function() {
document.body.appendChild(img);
}
}
function rubshFn() {
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
var startPos = null;
function startFn(e) {
startPos = {
x: e.pageX - this.offsetLeft,
y: e.pageY - this.offsetTop
};
ctx.beginPath();
ctx.moveTo(startPos.x, startPos.y)
canvas.addEventListener("mousemove", moveFn);
canvas.addEventListener("mouseup", upFn);
};
function moveFn(e) {
var moveX = e.pageX - this.offsetLeft,
moveY = e.pageY - this.offsetTop;
ctx.lineWidth = $("#range").value;
ctx.strokeStyle = $("#color").value;
ctx.lineTo(moveX, moveY);
ctx.stroke();
};
function upFn() {
canvas.removeEventListener("mousemove", moveFn);
}
</script>
</body>
</html>