Brownman Revival
Brownman Revival

Reputation: 3850

drawing polygon in canvas jquery html

var c2 = document.getElementById('c').getContext('2d');
c2.fillStyle = '#f00';
c2.beginPath();
c2.moveTo(200, 20);
c2.lineTo(200, 30);
c2.lineTo(300, 100);
c2.lineTo(400, 90);
c2.closePath();
c2.fill();

Found this tutorial to draw a polygon in canvas. I don't really understand how it works my condition in making my polygon is the location(north,south,east,west) and the length of the sides.

For example i want 50px north 50px south 50px east 50px west then it will be square how can i achieve this using this sample code any idea is appreciated or If you can point me to a better solution for example using jquery i would be happy to try the idea

Upvotes: 0

Views: 1710

Answers (2)

Naeem Shaikh
Naeem Shaikh

Reputation: 15725

what you pass inside moveto and lineto function is xx and y co ordinates, so if you want to draw a square of 50px width you can draw lines accordingly, here is the fiddle

var c2 = document.getElementById('c').getContext('2d');
c2.fillStyle = '#f00';
c2.beginPath();
c2.moveTo(200, 0);
c2.lineTo(200, 50);
c2.lineTo(250, 50);
c2.lineTo(250, 0);
c2.closePath();
c2.fill();

you can also create rectangles using rect method in canvas

http://jsfiddle.net/2ubafb9k/1/

c2.fillStyle="red";
c2.fillRect(10,10,50,50);

Upvotes: 1

mr rogers
mr rogers

Reputation: 3260

jQuery won't really help you. It might make finding the canvas easier (but only slightly)

// jQuery :
var c2 = $('c')[0].getContext('2d')

// vanilla javascript (as you have it()
var c2 = document.getElementById('c').getContext('2d');    

Here is the canvas code to render a 50px square starting at point 10, 10.

var c2 = document.getElementById('my_canvas').getContext('2d');
c2.fillStyle = '#f00';
c2.beginPath();
c2.moveTo(10, 10);
c2.lineTo(10, 60);
c2.lineTo(60, 60);
c2.lineTo(60, 10);
c2.closePath();
c2.fill();
<canvas id="my_canvas"></canvas>

If you want methods like north, south, east, and west, you could build a Javascript class that knows the current point and does the appropriate math. You might look into fabric.js which is an object oriented wrapper on the canvas methods.

Upvotes: 1

Related Questions