我试图通过单击并拖动鼠标指针来绘制一个圆.你在PowerPoint或其他方面的方式.圆圈的中心出现在奇怪的地方,我无法解释.
这是jsfiddle:https://jsfiddle.net/h8t3hfa2/2/
这就是我获得开始和结束位置的方式;
$('#c').mousedown(function(event) { var parentOffset = $(this).offset(); circle = new Circle(); circle.start['x'] = event.pageX - parentOffset.left; circle.start['y'] = event.pageY - parentOffset.top; }); $('#c').mouseup(function(event) { var parentOffset = $(this).offset(); circle.end['x'] = event.pageX - parentOffset.left; circle.end['y'] = event.pageY - parentOffset.top; circle.draw(canvas[0]); });
当我控制台记录中点时,它看起来是正确的,但圆圈显示在其他地方.有任何想法吗?
这是因为您使用CSS缩放画布.请记住,画布尺寸与画布CSS(样式)尺寸不同.
快速解决方法是均衡它们:
canvas.get(0).width = canvas.width(); canvas.get(0).height = canvas.height();
https://jsfiddle.net/h8t3hfa2/3/
var Circle = function() {
this.start = [];
this.end = [];
}
Circle.prototype.draw = function(canvas) {
var me = this;
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
var mid = me.getcenter();
var rad = me.getradius();
console.log(mid, rad);
ctx.beginPath();
console.log(mid['x'], mid['y']);
ctx.arc(mid['x'], mid['y'], rad, 0, 360);
ctx.stroke();
}
};
Circle.prototype.getcenter = function() {
var me = this;
//Check the start and end are set
var centerX = (me.start['x'] + me.end['x']) / 2;
var centerY = (me.start['y'] + me.end['y']) / 2;
return {
'x': centerX,
'y': centerY
};
};
Circle.prototype.getradius = function() {
var me = this;
var distX = Math.abs(me.start['x'] - me.end['x']);
var distY = Math.abs(me.start['y'] - me.end['y']);
return distX / 2;
};
var circle;
var canvas = $('#c');
// added only these two lines
canvas.get(0).width = canvas.width();
canvas.get(0).height = canvas.height();
$('#c').mousedown(function(event) {
var parentOffset = $(this).offset();
circle = new Circle();
circle.start['x'] = event.pageX - parentOffset.left;
circle.start['y'] = event.pageY - parentOffset.top;
});
$('#c').mouseup(function(event) {
var parentOffset = $(this).offset();
circle.end['x'] = event.pageX - parentOffset.left;
circle.end['y'] = event.pageY - parentOffset.top;
circle.draw(canvas[0]);
});
canvas {background-color: white;height: 100%;width: 100%;}