I’m trying to draw a rectangle by dragging mouse, basically follow this tutorial.
However, I found that if I specify the canvas dimension in px, it will not work. In contrast, if I use this html, this works fine:
<!DOCTYPE html>
<html>
<head>
<title>drag a rectangle</title>
<style>
#cvs {
width: 500;
height: 500;
border: 1px solid #666;
}
</style>
<script src="jquery-1.9.0.js"></script>
</head>
<body>
<canvas id="cvs"></canvas>
<script src="main.js"></script>
</body>
</html>
And this js:
$(document).ready(function() {
var canvas = document.getElementById('cvs');
var ctx = canvas.getContext('2d');
var rect = {};
var drag = false;
var mouseDown = function(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
console.log(rect.startX + ' ' + rect.startY);
drag = true;
};
var mouseUp = function(e) {
drag = false;
};
var draw = function() {
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
};
var mouseMove = function(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY;
console.log(rect.w + ' ' + rect.h);
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw();
}
};
function init() {
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
init();
});
It works fine. However, if I specify the dimension in px, i.e.,
#cvs {
width: 500px;
height: 500px;
border: 1px solid #666;
}
The mouse location and the rectangle no longer align. Also, the dimension in the viewport is also different. I suppose it’s a fundamental question, but what is the difference between specify the px or not? And how does that influence my drag rectangle behavior?
Tested locally on the latest Chrome.
To set the size of your canvas, use the canvas element attributes
widthandheight.When the page loads the canvas size is set to it’s
widthandheight. Ifstyle.widthand/orstyle.heightare set, the canvas will scale to fit the dimensions specified in these styles.Here is an example.
So now about your question. As I wrote above when you set
style.widthandstyle.heightas:The width and height will apply and the canvas will scale it’s size, so the point with coordinates
(x, y)won’t appear where you expect. For example, if you try to draw a point with coordinates(500, 500)you probably won’t see it at all, because simply your canvas coordinate system’s dimensions are less than that. When you don’t specifypxyou simply don’t provide valid width and height and your style does not apply correctly so your canvas is not scaled and everything works as you expect.