Tuval üzerine dikdörtgenler tıklayıp oluşturabileceğiniz basit bir sayfa oluşturmaya çalışıyorum. Kullanıcının fare tıklamalarını girdi olarak alır ve ardından tıklamanın x ve y öğelerinden bir dikdörtgen oluşturur. Bununla birlikte, dikdörtgeni bir miktar yana kapar ve neden emin değilim.Neden bu tuval üzerine oluşturduğum dikdörtgenler doğru yere konulmuyor?
Fiddle: https://jsfiddle.net/2717s53h/
HTML
<canvas id="cnv"></canvas>
CSS
#cnv{
width:99vw;
height:98vh;
background-color:#faefbd;
}
JAVASCRIPT
$(function() {
var canvas = $('#cnv');
var canvObj = document.getElementById('cnv');
var ctx = canvObj.getContext('2d');
var point1 = {};
var point2 = {};
canvas.click(function (e) {
console.log(e);
var x = e.pageX;
var y = e.pageY;
console.log(x);
console.log(y);
if (Object.keys(point1).length == 0)
{
point1.x = x;
point1.y = y;
}
else if (Object.keys(point2).length == 0)
{
point2.x = x;
point2.y = y;
console.log(point1);
console.log(point2);
var width = point2.x - point1.x;
var height = point2.y - point1.y;
width = width < 0 ? width * -1 : width;
height = height < 0 ? height * -1 : height;
ctx.fillRect(x, y, 10, 10);
point1 = {};
point2 = {};
}
});
});
[HTML5 JS fillRect() tuhaf davranışının olası kopyası] (http://stackoverflow.com/questions/13557429/html5-js-fillrect-strange-behavior) – ieaglle