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 width and height.
<canvas width="400" height="300">Not supported</canvas>
When the page loads the canvas size is set to it's width and height. If style.width and/or style.height are 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.width and style.height as:
#cvs {
width: 500px;
height: 500px;
border: 1px solid #666;
}
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 specify px you 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.
Related
I have this simple code for drawing with mouse in canvas. But if I try to style the canvas, like altering the width or centering, the pointer and line drawn get separated. How do I solve this?
JavaScript:
var el = document.getElementById('canvas');
var ctx = el.getContext('2d');
var isDrawing;
el.onmousedown = function(e) {
isDrawing = true;
ctx.moveTo(e.clientX, e.clientY);
};
el.onmousemove = function(e) {
if (isDrawing) {
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
}
};
el.onmouseup = function() {
isDrawing = false;
};
HTML:
CSS:
canvas {
border: 2px solid #ccc;
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 800px;
}
Here's a Fiddle
NEVER set canvas's width / height using css. It's really a bad idea. Always use the native width / height property of the canvas.
Also, you should probably be using e.offsetX and e.offsetY to get the x and y coordinates of the mouse.
Here's a working fiddle
I intend to draw free with the mouse cursor in canvas. My code seems to do the part with color but it doesn't take the exact coordinates of my current mouse position in canvas when i draw.
<body>
<canvas id="canvas" style=" width: 400; height: 400px; background-color:yellow; position: absolute; margin-left:100px; margin-top:30px"></canvas>
<script>
var Color = 'blue';
var Canvas = document.getElementById('canvas');
var Context = Canvas.getContext('2d');
$("canvas").on("mousemove",function(e){
X = e.clientX - canvas.offsetLeft;
Y = e.clientY - canvas.offsetTop;
Context.strokeStyle = Color;
Context.lineWidth = 3;
Context.lineCap = 'round';
Context.beginPath();
Context.moveTo(X,Y);
Context.lineTo(X,Y);
Context.fillRect(X,Y, 3,3)
Context.stroke();
Context.closePath();
});
</script>
</body>
https://jsfiddle.net/93L8mLnf/
I tested in console.log the coordinates and they are corect. I'm confused..
You need to synchronize the dimension of the canvas with the DOM element.
Add this:
Canvas.width = Canvas.clientWidth;
Canvas.height = Canvas.clientHeight;
Demonstration
You'll also notice the canvas isn't blurred anymore.
Note that this must be done every time the canvas DOM element changes size (usually because the window is resized) so when your element isn't of fixed size you should bind an event handler on the window resize event to do that synchronization again (and usually to redraw the content).
You have to add width and height by canvas attributes
see in fiddle
<canvas id="canvas" style="background-color:yellow;" width="250" height="250"></canvas>
I've set up a jsfiddle illustrating my situation: http://jsfiddle.net/j5o0w5qc/1/
Basically, I've got three nested HTML elements: a viewport div on the outside, a stage div in the middle, and a canvas on the inside. The stage div provides a perspective setting for 3d transformations applied to the canvas. The viewport has overflow: hidden; so we don't see anything outside of the viewport. It also has a listener attached, listening for mousedown.
In my actual app that I'm building, the canvas might be transformed to any arbitrary 3d transformation, involving translation and rotation in 3d space. What I would like to happen is for the viewport div to intercept a click, and draw a spot on the canvas in the place you clicked. I'm intercepting the event with the viewport div, and I'm using offsetX and offsetY in Chrome. This works great for Chrome, but I know I can't rely on offsetX and offsetY in other browsers, so I'd like to use pageX and pageY, normalized via jQuery, but I'm not sure quite how to do that.
What I've currently got in the jsfiddle works great in Chrome, except when you click in the viewport NOT on the canvas. When you click on the canvas, it draws a dot there, regardless of the canvas's transformation. Chrome is doing all the hard work and giving me exactly what I want with offsetX and offsetY. However, when you click in the viewport NOT on the canvas, I guess it's giving me offsetX and offsetY values relative to the viewport, rather than the canvas, and then interpreting that and drawing a dot on the canvas. For example, if I transform the canvas and then click in the upper right corner of the viewport, a dot appears in the upper right corner of the canvas, regardless of where that corner actually appears on the page.
In Firefox, however, it works great as long as there is no transformation applied to the canvas, but as soon as the canvas is transformed, all of a sudden, the dot being drawn is displaced, and I can't figure out how to take my pageX and pageY values and figure out exactly where in the canvas I am clicking.
Does anyone have any brilliant solutions? I've been bashing my head against this problem for far too long. I'm pretty sure I need to manually calculate some 3d transformation matrices or something, and I've spent hours writing methods to return the inverse of a matrix, and to multiply a matrix by a vector, and all sorts of stuff, but none of it has actually solved the problem for me, and I'm not sure what I'm missing.
Stackoverflow says code is required with jsfiddle links, so here's all my code:
HTML:
<div id="viewport">
<div id="stage">
<canvas id="myCanvas" width="300" height="300"></canvas>
</div>
</div>
<div id="stuff">
<button onclick="transformMe()">Transform</button>
<input id="blah" type="text" size="45"></input>
</div>
CSS:
#viewport, #stage, #myCanvas {
width: 300px;
height: 300px;
position: absolute;
top: 0;
left: 0;
}
#viewport {
border: 1px solid #000;
overflow: hidden;
}
#stage {
perspective: 1000px;
transform-style: preserve-3d;
}
#myCanvas {
background-color: green;
transform-style: preserve-3d;
}
#stuff {
position: absolute;
top: 350px;
}
Javascript:
var counter = 0;
$('#viewport').mousedown(function _drawOnCanvas (e)
{
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var xpos, ypos;
if (typeof e.offsetX=='undefined')
{
xpos = e.pageX - $('#myCanvas').offset().left;
ypos = e.pageY - $('#myCanvas').offset().top;
}
else
{
xpos = e.offsetX;
ypos = e.offsetY;
}
ctx.fillRect(xpos-5, ypos-5, 10, 10);
});
function transformMe()
{
counter++;
var angle = (counter * 30) % 360;
$('#myCanvas').css('transform','perspective(1000px) rotate3d(5,6,7,' + angle + 'deg)');
$('input').val('counter: ' + counter + ', angle: ' + angle);
};
For Firefox, you can use event.layerX and event.layerY. Think of them as Firefox's versions of offsetX & offsetY.
DEMO: http://jsfiddle.net/dirtyd77/j5o0w5qc/3/
JAVASCRIPT:
var counter = 0;
$('#viewport').mousedown(function _drawOnCanvas (e)
{
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var xpos, ypos;
if (typeof e.offsetX=='undefined')
{
xpos = e.originalEvent.layerX;
ypos = e.originalEvent.layerY;
}
else
{
xpos = e.offsetX;
ypos = e.offsetY;
}
ctx.fillRect(xpos-5, ypos-5, 10, 10);
});
function transformMe()
{
counter++;
var angle = (counter * 30) % 360;
$('#myCanvas').css('transform','perspective(1000px) rotate3d(5,6,7,' + angle + 'deg)');
$('input').val('counter: ' + counter + ', angle: ' + angle);
};
If you change viewport to myCanvas in line 3 of the either Kyle S or Dom's jsfiddles:
$('#myCanvas').mousedown(function _drawOnCanvas (e)
it no longer places a dot when you "click in the viewport NOT on the canvas."
It seems there's a new issue with Firefox - if there's a transformation it only lets you paint on half ( the bottom left of diagonal - but depends on transformation ).
I have done a very tiny example with canvas, it's available on JsFiddle:
http://jsfiddle.net/yPtr5/
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
#myCanvas {
width: 100%;
height: 100%;
display: block;
}
</style>
</head>
<body>
<canvas id="myCanvas">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var canvas = document.getElementById( "myCanvas" );
var context = canvas.getContext( "2d" );
context.id = "myContext";
context.beginPath();
context.arc( 95, 50, 40, 0, 2 * Math.PI );
context.stroke();
setTimeout( function() {
var rectWidth = 150;
var rectHeight = 75;
context.fillStyle = "blue";
context.fillRect( rectWidth / -2, rectHeight / -2, rectWidth, rectHeight );
}, 2000 );
</script>
</body>
</html>
As you are able to see, the rendering result has a very low quality:
So, I'm wondering, how can I draw various figures using Canvas in a good quality, I don't want to draw in small size, I want to draw in 100% size of page.
So, maybe I didn't define some anti aliasing filter or something else?
Thanks!
Problem
In most general cases we should avoid using CSS to set the canvas size.
The default size of canvas is 300 x 150 pixels (bitmap). If you set the size using CSS we'll just end up scaling those 300 x 150 pixels meaning the browser will start interpolating and smoothing the image, which is why you end up with a blurry result.
Solution
Remove these from the CSS-rule:
#myCanvas {
/*width: 100%;
height: 100%;*/
display: block;
}
and set the size in JavaScript like this:
var canvas = document.getElementById( "myCanvas" );
canvas.width = window.innerWidth; // equals window dimension
canvas.height = window.innerHeight;
You can of course set any other size you need (in pixels). You probably want to define position (i.e. fixed or absolute) for the canvas' CSS as well if your goal is full window size.
Hope this helps.
The height and width need to be set on the height and width attributes of the canvas tag and not in CSS. Any CSS sizing of the canvas element merely stretches the canvas and does not size it properly.
<canvas id="canvas" width="500px" height="500px">
Have a look at this project that I posted on my site: Creating an HTML5 Paint App
It includes a functionto resize the canvas when the browser window size changes (which you would have to modify):
this.onScreenSizeChanged = function (forceResize) {
if (forceResize || (this.canvas.width != window.innerWidth /*||
this.canvas.height != window.innerHeight*/)) {
var image = this.context.getImageData(0, 0,
this.canvas.width, this.canvas.height);
this.canvas.width = (window.innerWidth);
this.canvas.height = (window.innerHeight);
this.context.putImageData(image, 0, 0);
}
}
this.onScreenSizeChanged(true);
In my case, it was a problem with the screen pixel ratio.
To solve it, I created a canvas with a higher pixel ratio as follows:
function createHiPPICanvas(w, h) {
let ratio = window.devicePixelRatio;
let cv = document.createElement("canvas");
cv.width = w * ratio;
cv.height = h * ratio;
cv.style.width = w + "px";
cv.style.height = h + "px";
cv.getContext("2d").scale(ratio, ratio);
return cv;
}
Then I also increased accordingly the pixel ratio of the images used inside of the canvas.
I'm trying to draw a rectangle by a user click, mouse move, and click. There are two problems with my code.
Firstly, after one rectangle is drawn it is automatically assumed that another one will be drawn. Secondly, the starting point on the second rectangle is the last click that created the first rectangle.
http://jsbin.com/uqonuw/3/edit
You were close. So, the question isn't really about the "canvas" element in HTML5, but a canvas that is really a div.
http://jsfiddle.net/d9BPz/546/
In order for me to see what your code was trying to accomplish, I had to tidy it up. What needed to happen was tracking of the square element.
We are doing one of two things everytime we click on the canvas. We are either creating a rectangle element, or finishing a rectangle element. So, when we're finished it makes sense to set 'element' (previously named 'd') to null. When creating an element, we have to assign the new DOM element to 'element'.
Everytime the mouse moves, we want to get the mouse position. If the element is in the process of creation (or "not null"), then we need to resize the element.
Then we wrap it all up in a function, and that's all there is to it:
function initDraw(canvas) {
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
Usage: Pass the block-level element that you would like to make a rectangle canvas.
Example:
<!doctype html>
<html>
<head>
<style>
#canvas {
width:2000px;
height:2000px;
border: 10px solid transparent;
}
.rectangle {
border: 1px solid #FF0000;
position: absolute;
}
</style>
</head>
<body>
<div id="canvas"></div>
<script src="js/initDraw.js"></script>
<script>
initDraw(document.getElementById('canvas'));
</script>
</body>
</html>
Here's how to click-move-click to create a rectangle
Create these variables:
var isDrawing=false;
var startX;
var startY;
In your mousedown event handler:
If this is the starting click, set the isDrawing flag and set the startX/Y.
If this is the ending click, clear the isDrawing flage and draw the rectangle.
You might also want to change the mouse cursor so the user knows they are drawing.
if(isDrawing){
isDrawing=false;
ctx.beginPath();
ctx.rect(startX,startY,mouseX-startX,mouseY-startY);
ctx.fill();
canvas.style.cursor="default";
}else{
isDrawing=true;
startX=mouseX;
startY=mouseY;
canvas.style.cursor="crosshair";
}
Here is a Fiddle: http://jsfiddle.net/m1erickson/7uNfW/
Instead of click-move-click, how about using drag to create a rectangle?
Create these variables:
var mouseIsDown=false;
var startX;
var startY;
In your mousedown event handler, set the mouseIsDown flag and set the startX/Y.
Optionally, change the cursor so the user knows their dragging a rectangle.
mouseIsDown=true;
startX=mouseX;
startY=mouseY;
canvas.style.cursor="crosshair";
In your mouseup event handler, clear the mouseIsDown flag and draw the rect
If you changed the cursor, change it back.
mouseIsDown=false;
ctx.beginPath();
ctx.rect(startX,startY,mouseX-startX,mouseY-startY);
ctx.fill();
canvas.style.cursor="default";
For those who encountered the scrolling problem, I've found a fix.
You need to get the offset (using window.pageYOffset) and reduce it from the mouse position in any of the recommended snippets given. You should take it off from the height as well.
i was also working on a project, so here's my code
enjoy.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Selection</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<style>
body {
margin: 0px;
background-color: #f1f1f1;
}
canvas {
border: none;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="500"></canvas>
<div id="output"></div>
<script>
//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
//Mousedown
$(canvas).on('mousedown', function(e) {
last_mousex = parseInt(e.clientX-canvasx);
last_mousey = parseInt(e.clientY-canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function(e) {
mousedown = false;
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
//Mousemove
$(canvas).on('mousemove', function(e) {
mousex = parseInt(e.clientX-canvasx);
mousey = parseInt(e.clientY-canvasy);
if(mousedown) {
ctx.clearRect(0,0,canvas.width,canvas.height); //clear canvas
ctx.beginPath();
var width = mousex-last_mousex;
var height = mousey-last_mousey;
ctx.rect(last_mousex,last_mousey,width,height);
//ctx.fillStyle = "#8ED6FF";
ctx.fillStyle = 'rgba(164, 221, 249, 0.3)'
ctx.fill();
ctx.strokeStyle = '#1B9AFF';
ctx.lineWidth = 1;
ctx.fillRect(last_mousex, last_mousey, width, height)
ctx.stroke();
}
//Output
$('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);
});
</script>
</body>
</html>
Below is the solution I created in React. There might be some corner cases but it is working as per my knowledge.
Solution approach.
You must have start (x,y position) and the end (x,y) position
Once the user clicks on the cell capture cell number and column number start (x,y), this will happen on the mouseDown event
Then the user starts moving the mouse, in that case capture the cell number and the row number end (x,y) respectively.
Now the div draw logic comes where the condition would highlight the cell if the below condition is true.
i = cellNumber
i >= Math.min(start,end) && i <= Math.max(start,end) && i%4 <= Math.max(startY, endY)
https://codesandbox.io/s/still-field-0q760y?file=/src/App.js