我想創建一個簡單的頁面,您可以點擊並在畫布上創建矩形。它將用戶的鼠標點擊作爲輸入,然後從點擊的x和y創建一個矩形。但是,它將矩形放在一邊一些,我不知道爲什麼。爲什麼我在這個畫布上創建的矩形沒有放在正確的位置?
小提琴: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()奇怪的行爲](http://stackoverflow.com/questions/13557429/html5-js-fillrect-strange-behavior) – ieaglle