如何使用JavaScript绘制x/y位置的点

9

我想以二维方式绘制点(每个点都有x和y坐标)。我想知道是否有一个库或项目可以做到这一点,以便我不必从头开始构建。


你需要轴吗?为点提供上下文? - Crescent Fresh
是的...实际上我需要展示更多的东西,就像一个被分成四个象限的正方形,除了坐标轴。 - Tam
你是在使用<canvas>还是SVG? - James
我相信SVG,因为我没有使用HTML5。 - Tam
6个回答

15

使用Canvas标签是实现此目的的最佳方式。以下是创建Canvas的示例:

// Create a canvas that extends the entire screen
// and it will draw right over the other html elements, like buttons, etc
var canvas = document.createElement("canvas");
canvas.setAttribute("width", window.innerWidth);
canvas.setAttribute("height", window.innerHeight);
canvas.setAttribute("style", "position: absolute; x:0; y:0;");
document.body.appendChild(canvas);

//Then you can draw a point at (10,10) like this:

var ctx = canvas.getContext("2d");
ctx.fillRect(10,10,1,1);

此外,您可以使用ImageData操纵屏幕上的所有像素。

https://developer.mozilla.org/zh-CN/docs/Web/Guide/HTML/Canvas_tutorial/Drawing_shapes


如果矩形稍微大一点,它会更容易找到,你可以尝试使用 ctx.fillRect(10,10,10,10); - kkron

4

2

Raphaël是一个小型的JavaScript库,可简化您在Web上使用矢量图形的工作。


2
如果您已经在使用jQuery,那么Flot是一种非常简单(但功能强大)的绘制图表的方法。
您还可以查看Google Charts API -- 保证跨浏览器:它会给您提供一个作为图像的图表,而不是canvas或VML等。

1

最简单的方法:

point(30,30)

这段 JavaScript 代码使用 p5js,完整示例:

HTML:

<html>
  <head>
    <script src="p5.min.js"></script>
    <script src="sketch.js"></script>
  </head>
  <body style="margin: 0px;">
    <main>
    </main>
  </body>
</html>

sketch.js:

function preload() {
}

function setup() {
  createCanvas(window.innerWidth, window.innerHeight);
}

function draw() {
  background(0);
  stroke('white'); 
  strokeWeight(10);
  point(window.innerWidth/2,window.innerHeight/2);
}

更复杂的文章: http://en.jkeks.ru/javascript-how-to-draw-a-point-on-the-screen/

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接