<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.0.5/vue.min.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<div id=app style="overflow: scroll">
<div id=menu style="position: fixed; top: 0; left: 0">
<button @click="mode='select'">select</button>
<button @click="mode='rect'">rect</button>
</div>
<canvas style = "margin: 24px 4px 4px 4px; background: aliceblue" :class = "{ drawRect: mode == 'rect' }"
:width = "extent[ 0 ]" :height = "extent[ 1 ]" @mousedown = "mouseDown" @mousemove = "mouseMove" @mouseup = "mouseUp" @keyup.esc = "keyUpESC"/>
</div>
<script src="script.js"></script>
</body>
</html>
var app = new Vue({
el: "#app",
data: () => ({
b: null,
c: null,
mode: 'select',
elements: []
}),
computed: {
extent() {
return [300, 300]
},
canvas() {
return this.$el.getElementsByTagName('canvas')[0]
},
ctx() {
return this.canvas.getContext('2d')
},
dragRect() {
return (!this.b || !this.c) ? null : [this.b.offsetX, this.b.offsetY, this.c.offsetX - this.b.offsetX, this.c.offsetY - this.b.offsetY]
}
},
methods : {
draw() {
this.ctx.clearRect(0, 0, ...this.extent)
for (let _ of this.elements) this.ctx.strokeRect(..._)
if (!this.dragRect) return
switch (this.mode)
{
case 'rect':
this.ctx.setLineDash([1])
this.ctx.strokeRect(...this.dragRect)
this.ctx.setLineDash([])
break
}
},
mouseDown(_) {
this.b = _
this.draw()
},
mouseMove(_) {
this.c = _
this.draw()
},
mouseUp(_) {
this.c = _
switch (this.mode)
{
case 'rect':
this.elements.push(this.dragRect)
break
}
this.b = null
this.draw()
},
keyUpESC(_) {
this.mode = 'select'
this.draw()
}
},
mounted() {
this.canvas.setAttribute('tabindex', 0)
this.draw()
}
})
/* Styles go here */
.drawRect {
cursor: crosshair
}