简体   繁体   English

在画布jQuery HTML中绘制多边形

[英]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 For example i want 50px north 50px south 50px east 50px west那么这将是方形的。我如何使用此示例代码来实现此目的,如果您对我的想法有所感激,或者如果您可以将我引向更好的解决方案,例如使用jquery,我将很乐于尝试这个主意

jQuery won't really help you. jQuery不会真正帮助您。 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. 这是从10、10点开始渲染50px正方形的画布代码。

 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. 如果要使用诸如北,南,东和西之类的方法,则可以构建一个知道当前点并进行适当数学运算的Javascript类。 You might look into fabric.js which is an object oriented wrapper on the canvas methods. 您可能会研究一下fabric.js ,它是canvas方法上的一个面向对象的包装器。

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 在moveto和lineto函数内部传递的是xx和y坐标,因此,如果要绘制50px宽度的正方形,则可以相应地绘制线, 是小提琴

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 您还可以在画布中使用rect方法创建矩形

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM