A web-based drawing app
git clone git://soophie.de/outline
blob: 4f7c02b0bc1e1698151a889288b319569ebc7db9 (2488 bytes)[doc][blame][raw]
1
import { COLORS } from '../constant.js';3
let active;4
let point_list = [];6
let canvas;7
let overlay;8
let memory;10
function init() {11
canvas = document.querySelector('#canvas');12
overlay = document.querySelector('#overlay');13
memory = document.createElement('canvas');14
fit(canvas);15
fit(overlay);16
fit(memory);17
window.addEventListener('resize', function(event) {18
resize(canvas);19
resize(overlay);20
resize(memory);21
});22
}24
function fit(canvas) {25
canvas.width = window.innerWidth;26
canvas.height = window.innerHeight;27
}29
function get(canvas) {30
return canvas.getContext('2d');31
}33
function get_canvas() {34
return canvas;35
}37
function resize(canvas) {38
let g = get(canvas);39
let image_data = g.getImageData(0, 0, canvas.width, canvas.height);40
fit(canvas);41
g.putImageData(image_data, 0, 0);42
}44
function clear() {45
get(canvas).clearRect(0, 0, canvas.width, canvas.height);46
get(memory).clearRect(0, 0, memory.width, memory.height);47
}49
function on_press(event) {50
active = true;51
point_list.push({52
x: event.layerX,53
y: event.layerY54
});55
}57
function on_move(event, state) {58
if(active) {59
get(canvas).clearRect(0, 0, canvas.width, canvas.height);60
get(canvas).drawImage(memory, 0, 0);61
point_list.push({62
x: event.layerX,63
y: event.layerY64
});65
draw_curve(state);66
}67
}69
function on_release(event) {70
if(active) {71
if(event.type === 'pointerup') {72
active = false;73
}74
get(memory).clearRect(0, 0, memory.width, memory.height);75
get(memory).drawImage(canvas, 0, 0);76
point_list = [];77
}78
}80
function draw_curve(state) {81
let g = get(canvas);82
g.lineJoin = 'round';83
g.lineCap = 'round';84
g.lineWidth = 2 * state.radius;85
g.strokeStyle = COLORS[state.color] + 'BB';86
if(point_list.length < 3) {87
return;88
}89
if(point_list.length < 3) {90
g.beginPath();91
g.arc(point_list[0].x + 0.5, point_list[0].y + 0.5, g.lineWidth / 2, 0, Math.PI * 2, !0);92
g.closePath();93
g.fill();94
return;95
}96
g.beginPath();97
g.moveTo(point_list[0].x + 0.5, point_list[0].y + 0.5);98
let i;99
for(i = 1; i < point_list.length - 2; i++) {100
let dx = (point_list[i].x + point_list[i + 1].x);101
let dy = (point_list[i].y + point_list[i + 1].y);102
g.quadraticCurveTo(point_list[i].x + 0.5, point_list[i].y + 0.5, (dx / 2) + 0.5, (dy / 2) + 0.5);103
}104
g.quadraticCurveTo(point_list[i].x + 0.5, point_list[i].y + 0.5, point_list[i + 1].x + 0.5, point_list[i + 1].y + 0.5);105
g.stroke();106
}108
export default {109
init,110
fit,111
get,112
get_canvas,113
resize,114
clear,115
on_press,116
on_move,117
on_release,118
draw_curve119
};