签名
const canvas = document.querySelector('canvas'),
saveBtn = document.querySelector('.save'),
colorEl = document.querySelector('.color'),
increaseBtn = document.querySelector('.increase'),
decreaseBtn = document.querySelector('.decrease'),
clearBtn = document.querySelector(".clear"),
ctx = canvas.getContext('2d'),
sizeEl = document.querySelector('.size');
let size = 10,
color = colorEl.value,
x, y,
isPressed = false;
function init() {
bindEvent()
}
function bindEvent() {
clearBtn.addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
})
saveBtn.addEventListener('click', () => {
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = '测试.png';
link.click();
link.remove()
})
increaseBtn.addEventListener('click', e => {
size += 5;
if (size > 50) {
size = 50;
}
sizeEl.innerHTML = size;
})
decreaseBtn.addEventListener('click', e => {
size -= 5;
if (size < 5) {
size = 5
}
sizeEl.innerHTML = size;
})
colorEl.addEventListener('change', e => color = e.target.value);
canvas.addEventListener('mousedown', down)
canvas.addEventListener('mousemove', move)
canvas.addEventListener('mouseup', up)
}
function down(e) {
console.log(e);
isPressed = true;
x = e.offsetX;
y = e.offsetY;
}
function up() {
isPressed = false
}
function move(e) {
if (isPressed) {
const x2 = e.offsetX;
const y2 = e.offsetY;
drawCircle(x2, y2);
drawLine(x, y, x2, y2);
x = x2;
y = y2;
}
}
function drawLine(mX, mY, toX, toY) {
ctx.beginPath();
ctx.lineWidth = size * 2
ctx.moveTo(mX, mY);
ctx.lineTo(toX, toY);
ctx.strokeStyle = color;
ctx.stroke()
}
function drawCircle(x, y) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(x, y, size, 0, Math.PI * 2, false);
ctx.fill()
}
init()
画圆
const query = function (selector) {
return document.querySelector(selector);
}
const canvas2 = query('.canvas2')
const canvas3 = query('.canvas3');
drawCirecle(canvas2, 5, '#ccc');
function drawCirecle(canvas, lineWidth, color) {
const ctx = canvas.getContext('2d');
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, (canvas.width - lineWidth) / 2, 0, Math.PI * 2, false);
ctx.stroke()
}
autoDrawCircle(canvas3, 5, 'orange', 60);
function autoDrawCircle(canvas, lineWidth, color, angle) {
const ctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
center = (w - lineWidth) / 2;
percent = 0;
function run() {
ctx.clearRect(0, 0, w, h);
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.beginPath();
ctx.arc(w / 2, h / 2, center, 0, Math.PI * 3.6 * percent / 180, false);
ctx.stroke();
ctx.rotate(90 * Math.PI / 180);
console.log(ctx);
ctx.fillStyle = color;
ctx.textAlign = "center"
ctx.textBaseline = "middle"
ctx.font = "30px sans-serif"
ctx.fillText(percent + '%', center, -center)
if (percent === angle) {
return
}
percent++;
requestAnimationFrame(run)
}
run()
}