-
Notifications
You must be signed in to change notification settings - Fork 9
/
canvas.js
97 lines (83 loc) · 2.54 KB
/
canvas.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var ImgCanvas = function(canvas) {
var self = this,
draw;
this.canvas = canvas;
this.context = canvas.getContext("2d");
this.typeDraw = 'line';
draw = this[this.typeDraw]();
var mouseEvt = function(event) {
if (event.offsetX || event.offsetX == 0) {
event._x = event.offsetX;
event._y = event.offsetY;
}
var func = draw[event.type];
if (func) {
func(event);
}
};
this.canvas.addEventListener('mousedown', mouseEvt, false);
this.canvas.addEventListener('mousemove', mouseEvt, false);
this.canvas.addEventListener('mouseup', mouseEvt, false);
}
ImgCanvas.prototype = {
setBackground : function(background) {
var self = this;
if (!background) {
background = this.canvas.toDataURL("image/png");
}
self.background = background;
var image = new Image();
image.src = background;
image.onload = function() {
self.context.drawImage(
image,
0,
0,
self.canvas.getAttribute("width").replace("px", ""),
self.canvas.getAttribute("width").replace("px", "") * image.height / image.width
);
}
},
line : function() {
var self = this;
this.start = false;
this._mousemove = function(event) {
if (!this.start) {
return;
}
this.context.strokeStyle = "#ff0000";
this.context.lineTo(event._x, event._y);
this.context.stroke();
};
this._mousedown = function(event) {
this.context.beginPath();
this.context.moveTo(event._x, event._y);
this.start = true;
};
this._mouseup = function(event) {
if (!this.start) {
return;
}
this._mousemove(event);
this.start = false;
};
return {
mousedown : function(event) {
self._mousedown(event);
},
mousemove : function(event) {
self._mousemove(event);
},
mouseup : function(event) {
self._mouseup(event);
}
}
},
getImg : function() {
var dataURL = this.canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
},
getDataUrl : function() {
return this.canvas.toDataURL("image/png");
}
}