I know I can draw arc with arc function of canvas but when I increase the size of that arc it changes its start and end x,y points. So I was thinking if we can draw arc with some other way keeping its start end points fixed while increasing it size.
Edit
Below is the images showing what I am looking for. First image shows a rectangle. when its side is stretched it changed to circle(2nd image). when side is stretched further it changed to big circle. At in all images you can see that end points of circle are joined to corners of rectangle. This is what I want to do.
1st Image
2nd Image
3rd Image
Or you can see this video to understand what I am looking to do.
What I have done
This fiddle shows result of my work.
To draw rectangle just click and drag your mouse.
Here is the code
I believe you're looking for something like this:
draw(0);
$('#range').on('change', function(){
range = parseInt($(this).val());
draw(range)
})
function draw(val){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d'),
x = 100,
y = 50,
d;
context.clearRect(0, 0, canvas.width, canvas.height);
d = Math.sqrt(Math.pow(val,2) + Math.pow(50,2));
context.beginPath();
context.lineWidth = 1;
context.arc(x,y+val,d,0,2*Math.PI);
// line color
context.strokeStyle = 'black';
context.stroke();
// Cut off the top of the circle.
context.clearRect(0, 0, canvas.width, y);
// This stuff's just to show some dots
context.fillStyle = 'red';
context.fillRect(x-1,y-1,2,2); // Middle
context.fillRect(x-52,y-2,4,4);//Target point 1
context.fillRect(x+48,y-2,4,4);// Target point 2
context.fillRect(x-2,y+d+val-2,4,4); // Point on circle
context.fillStyle = 'black';
}
Working sample
There are a couple disadvantages to this is that it gets "slower" the closer you get to the circle, because the circle's getting exponentially larger in the hidden section (The slider's controlling it's size), and that it doesn't work for diagonal lines as it is right now.
Other than that, it works like expected.
Check this : http://jsfiddle.net/KZBzq/4/
Updated answer with bezierCurveTo
HTML
<label>Range :</label>
<input type="range" name="points" value="0" min="0" step="1" max="100" id="range">
<canvas id="myCanvas" width="578" height="250"></canvas>
JS
draw(100);
$('#range').on('change', function(){
range = parseInt($(this).val());
draw(100-range)
})
function draw(val){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d'),
x = 100,
y = 100,
cp1x = x/2,
cp2x = y/2,
cp1y = val,
cp2y = val;
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.lineWidth = 1;
context.moveTo(25 , x);
context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);
// line color
context.strokeStyle = 'black';
context.stroke();
}
Now x and Y are fixed. Is this was your requirement?
Related
i made 2 deference size html canvas to drawing
First canvas = width : 400px,height:200px
Second canvas = width : 200px,height :100px
Now when i drawing in first html canvas i send that coordinates(x1,y1,x2,y2) to second canvas.
When first canvas coordinates send in second canvas it's not drawing in same place as first canvas.
is there way to equal first canvas coordinates to second one without changing canvas width and height .
ctx.beginPath();
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.strokeStyle = "red";
ctx.moveTo(coord.x, coord.y);
ctx.lineTo(ncoord.x , ncoord.y);
ctx.stroke();
//SECOUND CANVAS
ctx2.beginPath();
ctx2.lineWidth = 5;
ctx2.lineCap = 'round';
ctx2.strokeStyle = "red";
ctx2.moveTo(coord.x, coord.y);
ctx2.lineTo(ncoord.x , ncoord.y);
ctx2.stroke();
when user drwaing in canvas 1 i send that coordinates to both canvas. but in second canvas not drawing in same place as canvas 1.
Note : canvas 1 and 2 have deferent width and height.
I need to slove this without changing width height of the both canvas.
I hope I have made the right assumptions to answer your question. I created two different canvases of two different sizes. The coordinates only fit on the first, bigger, canvas.
You can transform the 'big' coordinates to 'small' coordinates by dividing the width or height of the bigger smaller canvases by the bigger canvases.
For example, the height of the big canvas is 200 but the height of the smaller one is 100. If you divide 100 / 200 you get 0.5. The 'small' coordinates should be half as high as the original ones. See for yourself below:
//just for testing purposes
var coord = {
x: 320,
y: 125
};
var ncoord = {
x: 220,
y: 90
};
function drawBig() {
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.strokeStyle = "red";
ctx.moveTo(coord.x, coord.y);
ctx.lineTo(ncoord.x, ncoord.y);
ctx.stroke();
}
function drawSmall() {
let bigCanvas = document.getElementById("canvas1");
let smallCanvas = document.getElementById("canvas2");
//Devide the dimensions of the big and small canvas in order to get the magnification factor:
let widthDimension = smallCanvas.width / bigCanvas.width;
let heightDimension = smallCanvas.height / bigCanvas.height
var ctx2 = smallCanvas.getContext("2d");
ctx2.beginPath();
ctx2.lineWidth = 5;
ctx2.lineCap = 'round';
ctx2.strokeStyle = "red";
//Transform the original coordinates to the right dimensions:
ctx2.moveTo(coord.x * widthDimension, coord.y * heightDimension);
ctx2.lineTo(ncoord.x * widthDimension, ncoord.y * heightDimension);
ctx2.stroke();
}
canvas {
border: 1px solid black;
}
<canvas id="canvas1" width="400" height="200"></canvas>
<hr>
<canvas id="canvas2" width="200" height="100"></canvas>
<button onclick="drawBig()">draw big canvas</button>
<button onclick="drawSmall()">draw small canvas</button>
Hope this helps! If not, please comment
I've tried 3 ways to make it, but the effect doesn't looks well.
copy and fill image then make offset. The demo is
var ctx = canvas.getContext('2d'),
img = new Image;
img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";
function draw() {
var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
s = 20, // thickness scale
i = 0, // iterator
x = 5, // final position
y = 5;
// draw images at offsets from the array scaled by s
for(; i < dArr.length; i += 2)
ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);
// fill with color
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = "red";
ctx.fillRect(0,0,canvas.width, canvas.height);
// draw original image in normal mode
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>
. When the outline width is large, the outline result will be wrong.
check the edge of image base on the Marching Squares algorithm. When the image shape is circle, the outline is with sawtooth. If make the outline more smoother, it won't fit the sharp shape like star.
copy and fill the image then scale it. When a image width is not equal with height, it doesn't work.
You can try with a math approach, without the offset array
var ctx = canvas.getContext('2d'),
img = new Image;
img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";
function draw() {
var s = 20, // thickness scale
x = 5, // final position
y = 5;
for (i=0; i < 360; i++)
ctx.drawImage(img, x + Math.sin(i) * s, y + Math.cos(i) * s);
// fill with color
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = "red";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// draw original image in normal mode
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>
My idea comes from the way we draw a circle using a string:
https://www.wikihow.com/Draw-a-Perfect-Circle-Using-a-Pin
Imagine that instead of a pencil at the end of the string we just have a shape
Here is a visual comparison of my approach and yours, also I'm showing a third approach scaling the image, there is really not a best one, it's just a matter of personal preference.
You could create a hybrid mode, if the hairline is important to you, get that portion of the image scaling it, then use a different way for the rest of the body.
I can draw a line as per direction but I am not being able to draw a text as per line direction. My paint will be like this...
You need to figure out how wide the text will be and that can be solved with:
ctx.measureText(text).width;
Then just create a funtion that draws lines on either side of it (and a arrow head). Finish everything off with rotating the whole canvas before drawing it, like so:
Original answer: http://jsfiddle.net/txrvLLjp
EDIT
New code allows for adding starting and stopping points instead.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var text = "Knows";
var TO_RADIANS = Math.PI / 180;
ctx.font = "12px Arial";
drawArrow(text,40,40,200,200);
function drawArrow(text,startX,startY,stopX,stopY) {
var deltaX = (stopX-startX);
var deltaY = (stopY-startY)
//calculating the total length of the line
var arrowLength=Math.sqrt(deltaX*deltaX+deltaY*deltaY);
//calculating the angle
var angle=Math.atan2(deltaY,deltaX) * 180 / Math.PI;
ctx.save();
ctx.translate(startX,startY);
ctx.rotate(angle*TO_RADIANS);
var textLength = ctx.measureText(text).width;
var padding=(arrowLength-textLength)/2;
ctx.moveTo(0,0);
ctx.lineTo(padding,0);
ctx.stroke();
ctx.fillText(text,padding,4);
ctx.moveTo(padding+textLength,0);
ctx.lineTo(padding+textLength+padding,0);
ctx.stroke();
//Arrow point below
ctx.moveTo(padding+textLength+padding,0);
ctx.lineTo(padding+textLength+padding-8,8);
ctx.stroke();
ctx.moveTo(padding+textLength+padding,0);
ctx.lineTo(padding+textLength+padding-8,-8);
ctx.stroke();
ctx.restore();
}
<canvas id="myCanvas" width="200" height="400"></canvas>
I'm trying to figure out how to rotate a single object on an html 5 canvas.
For example: http://screencast.com/t/NTQ5M2E3Mzct - I want each one of those cards to be rotated at a different degree.
So far, all I've seen are articles and examples that demonstrate ways to rotate the entire canvas. Right now, I'm guessing I'll have to rotate the canvas, draw an image, and then rotate the canvas back to it's original position before drawing the second image. If that's the case, then just let me know! I just have a feeling that there's another way.
Anyone have any idea?
I ran into the same problem in a recent project (where I kicked rotating aliens all over the place). I just used this humble function that does the same thing and can be used the same way as ctx.rotate but can be passed an angle. Works fine for me.
function drawImageRot(img,x,y,width,height,deg){
// Store the current context state (i.e. rotation, translation etc..)
ctx.save()
//Convert degrees to radian
var rad = deg * Math.PI / 180;
//Set the origin to the center of the image
ctx.translate(x + width / 2, y + height / 2);
//Rotate the canvas around the origin
ctx.rotate(rad);
//draw the image
ctx.drawImage(img,width / 2 * (-1),height / 2 * (-1),width,height);
// Restore canvas state as saved from above
ctx.restore();
}
Yay, my first answer!
Unfortunately in the HTML5 canvas element you can't rotate individual elements.
Animation works like drawing in MS Paint: You draw something, make a screen.. use the eraser to remove some stuff, draw something differently, make a screen.. Draw something else on top, make a screen.. etc etc.
If you have an existing item on the canvas - you'll have to erase it ( use ctx.fillRect() or clearRect() for example ), and then draw the rotated object.
If you're not sure how to rotate it while drawing in the first place:
ctx.save();
ctx.rotate(0.17);
// draw your object
ctx.restore();
To rotate a individual object you have to set the transformation matrix. This is really simple:
var context = document.getElementById('pageCanvas').getContext('2d');
var angle = 0;
function convertToRadians(degree) {
return degree*(Math.PI/180);
}
function incrementAngle() {
angle++;
if(angle > 360) {
angle = 0;
}
}
function drawRandomlyColoredRectangle() {
// clear the drawing surface
context.clearRect(0,0,1280,720);
// you can also stroke a rect, the operations need to happen in order
incrementAngle();
context.save();
context.lineWidth = 10;
context.translate(200,200);
context.rotate(convertToRadians(angle));
// set the fill style
context.fillStyle = '#'+Math.floor(Math.random()*16777215).toString(16);
context.fillRect(-25,-25,50,50);
context.strokeRect(-25,-25,50,50);
context.restore();
}
// Ideally use getAnimationFrame but for simplicity:
setInterval(drawRandomlyColoredRectangle, 20);
<canvas width="1280" height="720" id="pageCanvas">
You do not have a canvas enabled browser
</canvas>
Basically, to make an object rotate properly without having other shape rotating around, you need to:
save the context: ctx.save()
move the pivot point to the desired location: ctx.translate(200, 200);
rotate: context.rotate(45 * Math.PI / 180);
draw the shape, sprite, whatever: ctx.draw...
reset the pivot: ctx.translate(-200, -200);
restore the context to its original state: ctx.restore();
function spinDrawing() {
ctx.save();
ctx.translate(200, 200);
context.rotate(45 * Math.PI / 180);
ctx.draw //your drawing function
ctx.translate(-200, -200);
ctx.restore();
}
Caveats: After you translating , the origin of the canvas changed, which means when you drawing the shape, the coordinate of the shape should be aligned accordingly.
Shapes drawn outside the list mentioned above won´t be affected. I hope it helps.
This html/javascript code might shed some light on the matter:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="233" height="233" style="border:1px solid #d3d3d3;">
your browser does not support the canvas tag </canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var canvasWidth=233;
var canvasHeight=233;
var rectWidth=100;
var rectHeight=150;
var x=30;
var y=30;
var translateX= x+(rectWidth/2);
var translateY= y+(rectHeight/2);
ctx.fillRect(x,y,rectWidth,rectHeight);
ctx.translate(translateX,translateY);
ctx.rotate(5*Math.PI/64); /* just a random rotate number */
ctx.translate(-translateX,-translateY);
ctx.fillRect(x,y,rectWidth,rectHeight);
</script>
</body>
</html>
I find it helpful to see the math related to rotating, I hope this was helpful to you too.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="450" style="border:1px solid #d3d3d3;">
</canvas>
<Button id = "right" onclick = "rotateRight()">Right</option>
<Button id = "left" onclick = "rotateLeft()">Left</option>
<script src = "zoom.js">
</script>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
createRect();
function rotateRight()
{
ctx.save();
ctx.clearRect(0,0,500,450);
ctx.translate(c.width/2,c.height/2);
ctx.rotate(10*Math.PI/180 );
ctx.translate(-c.width/2,-c.height/2);
createRect();
}
function rotateLeft()
{
ctx.save();
ctx.clearRect(0,0,500,450);
ctx.translate(c.width/2,c.height/2);
ctx.rotate(-10*Math.PI/180 );
ctx.translate(-c.width/2,-c.height/2);
createRect();
}
function createRect()
{
ctx.beginPath();
ctx.fillStyle = "#AAAA00";
ctx.fillRect(250,250,90,50);
}
</script>
</body>
</html>
To rotate an object you can use rotate() method. Here the example how to rotate a rectangular object to 135 degrees of clockwise.
<script>
var canvas = document.getElementById('Canvas01');
var ctx = canvas.getContext('2d');
var rectWidth = 100;
var rectHeight = 50;
//create line
ctx.strokeStyle= '#ccc';
ctx.beginPath();
ctx.moveTo(canvas.width / 2, 0);
ctx.lineTo(canvas.width / 2, canvas.height);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(0, canvas.height/2);
ctx.lineTo(canvas.width, canvas.height/2);
ctx.stroke();
ctx.closePath();
// translate ctx to center of canvas
ctx.translate(canvas.width / 2, canvas.height / 2);
// rotate the rect to 135 degrees of clockwise
ctx.rotate((Math.PI / 180)*135);
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, rectWidth, rectHeight);
</script>
</body>
Here the demo and you can try yourself: http://okeschool.com/examples/canvas/html5-canvas-rotate
I found this question because I had a bunch of stuff on a canvas, drawn with canvas lines, painstakingly, and then decided some of them should be rotated. Not wanting to do a whole bunch of complex stuff again I wanted to rotate what I had. A simple solution I found was this:
ctx.save();
ctx.translate(x+width_of_item/2,y+height_of_item/2);
ctx.rotate(degrees*(Math.PI/180));
ctx.translate(-(x+width_of_item/2),-(y+height_of_item/2));
// THIS IS THE STUFF YOU WANT ROTATED
// do whatever it is you need to do here, moveto and lineto is all i used
// I would expect anything to work. use normal grid coordinates as if its a
// normal 0,0 in the top left kind of grid
ctx.stroke();
ctx.restore();
Anyway - it might not be particularly elegant but its a dead easy way to rotate one particular element onto your canvas.
Look at all those rotated elements!
PEN: https://codepen.io/jaredstanley/pen/gvmNye
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
var centerw = canvas.width/2;
var centerh = canvas.height/2;
var sq_w = 80;
//
ctx.beginPath();
//draw rectangle
ctx.rect(this.centerw-(sq_w/2), 0,sq_w, canvas.height);
//draw circle
ctx.arc(this.centerw, this.centerh, 185, 0, Math.PI * 2, true);
//fill
ctx.fill();
The shapes both draw but the intersection of the shapes is blank.
Looking to have one single, filled shape, but get the following result:[
REQUIREMENTS:
Cannot use CanvasRenderingContext2D.globalCompositeOperation as I'm using that for something else; this needs to be used as a single shape so i can use the shape to ...clip().
Note: when using two rect() calls it works, and when using two arc() calls it works, but mixing them seems to cause an issue.
Seems like it should be easy but I'm stumped, missing something basic I think. Thanks!
Path-direction matters
Simply remove (or set to false) the counter-clock wise flag on the arc() method as this will otherwise define the path the "opposite" direction affecting the default non-zero winding algorithm used for filling:
//ctx.arc(this.centerw, this.centerh, 185, 0, Math.PI * 2, true); ->
ctx.arc(this.centerw, this.centerh, 185, 0, Math.PI * 2);
A More Close Look at "Non-Zero Winding"
According to the non-zero winding rule we would add up winding counted from a point from where a line is "sent out". For each line intersection of the point's line we check the crossing line's direction and give it +1 for one direction, -1 if the opposite direction, and add those together.
To illustrate:
For the illustration on the left we can see that the sum of the directions of the two first line intersections (if point is placed left and center on y) will be 0 ("zero") so no fill for the center section. This would also happen if a point sent a line from center top and down through the shape.
However, in the illustration on the right the sum is non-zero when we come to the inner section so it too becomes filled.
Example: arc() uses clockwise direction instead
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
var centerw = canvas.width/2;
var centerh = canvas.height/2;
var sq_w = 120;
//
ctx.beginPath();
//draw rectangle
ctx.rect(centerw-(sq_w/2), 0,sq_w, canvas.height);
//draw circle
ctx.moveTo(centerw + 185, centerh); // create new sub-path (is unrelated, see below)
ctx.arc(centerw, centerh, 185, 0, Math.PI * 2); // <- don't use the CCW flag
//fill
ctx.fill();
<canvas id="c" width="500" height="500"></canvas>
Unrelated but something to have in mind: you would also want to create a new sub-path for the arc to avoid risking a line from a corner of the rect going to the start-angle point on the arc. Simply add this line before adding the arc:
ctx.moveTo(centerw + 185, centerh);
ctx.arc(centerw, centerh, 185, 0, Math.PI * 2);
ctx.beginPath();
//draw rectangle
ctx.rect(this.centerw - (sq_w / 2), 0, sq_w, canvas.height);
ctx.fill();
//draw circle
ctx.beginPath();
ctx.arc(this.centerw, this.centerh, 185, 0, Math.PI * 2, true);
//fill
ctx.fill();
The result you see happens because the standard operation on a surface contained by crossed paths, is to ignore.
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
var centerw = canvas.width/2;
var centerh = canvas.height/2;
var sq_w = 80;
//draw rectangle
ctx.fillRect(this.centerw-(sq_w/2), 0,sq_w, canvas.height);
//draw circle
ctx.arc(this.centerw, this.centerh, 185, 0, Math.PI * 2, true);
//fill
ctx.fill();
<canvas id='c' height=500 width=500/>
The shapes need to be filled between the rounds. Or, in the code snippet, I changed ctx.rect to ctx.fillRect.
Another approach would be to begin a new path before the arc.