Bài toán của mình đặt trong tình huống là một trái banh ‘hình chữ nhật’ va chạm và phản xạ từ thành bàn. Dĩ nhiên đoạn code như thế này thì vẫn chạy tốt
update: function () {
this.count++;
this.rect.x += this.rect.vx;
this.rect.y += this.rect.vy;
var wh = this.get_wh();
if (this.rect.x > wh.w || this.rect.x < 0) {//su kien cham tuong dung
this.rect.vx = -this.rect.vx;
}
if (this.rect.y > wh.h || this.rect.y < 0) {//su kien cham tuong ngang
this.rect.vy = -this.rect.vy;
}
},
Nhưng bây giờ mình muốn cài đặt một cái sự kiện: “cham_tuong”
thì cài đặt thế nào? Trong bài toán của mình.
Toàn bộ source code như sau:
<script>
class Rect {
constructor(x,y,w,h) {
this.name = "Rect";
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.vx = 0;
this.vy = 0;
}
draw(ctx) {
ctx.rect(this.x,this.y,this.w,this.h);
ctx.strokeStyle = 'blue';
ctx.stroke();
}
}
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
count: 0,
rect:null,
},
mounted: function () {
var canvas = this.get_canvas();
var wh = { w: canvas.width, h: canvas.height }
this.draw_rec(0, 0, wh.w, wh.h, 'blue');
this.rect = new Rect(0, 0, 20, 10);
this.rect.vx = 1;
this.rect.vy = 1;
this.run();
var el = this.$el;
$(el).find("canvas").bind('click', this.on_click);
//code here
//var event = new Event('cham_tuong');
//$(el).find("canvas").dispatchEvent(event);
//$(el).find("canvas").bind('cham_tuong', this.on_cham_tuong);
//end code here
},
methods: {
get_canvas: function () {
var el = this.$el;
var canvas = $(el).find("canvas")[0];
return canvas;
},
get_ctx: function () {
var el = this.$el;
var ctx = $(el).find("canvas")[0].getContext('2d');
return ctx;
},
get_wh: function () {
var canvas = this.get_canvas();
var wh = { w: canvas.width, h: canvas.height }
return wh;
},
on_click: function (e) {
//alert('click')
var x = e.offsetX;
var y = e.offsetY;
this.rect.x = x;
this.rect.y = y;
},
on_cham_tuong: function () {
alert('hi');
},
draw_rec: function (x1, y1, x2, y2, color) {
var ctx = this.get_ctx()
ctx.beginPath();
ctx.rect(x1, y1, x2, y2);
ctx.strokeStyle = color;
ctx.stroke();
},
draw_rec_fill: function (x1, y1, x2, y2, color, fill) {
var ctx = this.get_ctx()
ctx.beginPath();
ctx.strokeStyle = color;
ctx.fillStyle = fill;
ctx.fillRect(x1, y1, x2, y2);
},
draw: function () {
this.message = this.count;
var ctx = this.get_ctx()
this.draw_rec_fill(0, 0, this.get_wh().w, this.get_wh().h, 'red', 'yellow');
this.rect.draw(ctx);
},
update: function () {
this.count++;
this.rect.x += this.rect.vx;
this.rect.y += this.rect.vy;
var wh = this.get_wh();
if (this.rect.x > wh.w || this.rect.x < 0) {//su kien cham tuong dung
this.rect.vx = -this.rect.vx;
}
if (this.rect.y > wh.h || this.rect.y < 0) {//su kien cham tuong ngang
this.rect.vy = -this.rect.vy;
}
},
run: function () {
var that = this;
(function tick() {
that.update();
that.draw();
setTimeout(function () { that.run(); }, 37);
})();
}
}
})
Minh họa giao dien thế này