I'm currently a beginner in javascript and learning the canvas. I was wonder if anyone would explain why if you drew backwards from right to left, it shows the negative numbers in the inputs. Is there anyway to make it positive to display the real size of the rectangle regardless which direction you draw it in?
Here is the JS fiddle. https://jsfiddle.net/asn6wzw4/2/
The HTML
<form id="areaform">
<label for="wid">Width:</label>
<input id="wid" type="number">
<label for="hgt">Height:</label>
<input id="hgt" type="number">
<br/>
<label for="area1">Area:</label>
<output id="area"></output>
<br/>
<label for="perimeter1">Perimeter:</label>
<output id="perim"></output>
<br/>
<button onclick="getarea()" type="button">Get Area</button>
</form>
<div id="drawRectangle">
<canvas id="rectCanvas" width=500 height=500></canvas>
</div>
The JS
var canvas, context, startX, endX, startY, endY;
var mouseClicked = 0;
function mouseUp(e) {
if (mouseClicked !== 0) {
mouseClicked = 0;
var pos = getMousePos(canvas, e);
endX = pos.x;
endY = pos.y;
drawRectangle();
}
}
function mouseDown(e) {
mouseClicked = 1;
var pos = getMousePos(canvas, e);
startX = endX = pos.x;
startY = endY = pos.y;
drawRectangle();
}
function mouseXY(e) {
if (mouseClicked !== 0) {
var pos = getMousePos(canvas, e);
endX = pos.x;
endY = pos.y;
drawRectangle();
}
}
function drawRectangle() {
var width = endX - startX;
var height = endY - startY;
var offsetX = (width > 0);
var offsetY = (height > 0);
document.getElementById("wid").value = width;
document.getElementById("hgt").value = height;
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.rect(startX + offsetX, startY + offsetY, width, height);
context.fillStyle = "#88EF5E";
context.fill();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function init() {
canvas = document.getElementById("rectCanvas");
context = canvas.getContext("2d");
canvas.addEventListener("mousedown", mouseDown);
canvas.addEventListener("mousemove", mouseXY);
canvas.addEventListener("mouseup", mouseUp);
}
init();