好的,所以我对javascript的尴尬是不可知的。我知道我的红宝石和导轨相当坚固,但从来没有像我现在的项目那样广泛使用js。
我有一张画布上绘制的地图。在该地图上,我想要绘制多个位置标记(通过提供的功能)。我已经给它一个列表(通过铁轨)标记的位置。由于某种原因,它只绘制最后一个坐标。
javascript是从另一个来源即兴创作的,而不是我的。这只是有问题的部分:
function plotPosition(long,lat) {
// Grab a handle to the canvas
var canvas = document.getElementById('map'),
ctx;
// Canvas supported?
if (canvas.getContext) {
// Grab the context
ctx = canvas.getContext('2d');
ctx.beginPath();
// Draw a arc that represent the geo-location of the request
ctx.arc(
degreesOfLongitudeToScreenX(long),
degreesOfLatitudeToScreenY(lat),
5,
0,
2 * Math.PI,
false
);
// Point style
ctx.fillStyle = 'rgb(0,0,0)';
ctx.fill();
ctx.stroke();
}
}
function draw() {
// Main entry point got the map canvas example
var canvas = document.getElementById('map'),
ctx;
// Canvas supported?
if (canvas.getContext) {
ctx = canvas.getContext('2d');
// Draw the background
drawBackground(ctx);
// Draw the map background
drawMapBackground(ctx);
// Draw the map background
// drawGraticule(ctx);
// Draw the land
drawLandMass(ctx);
<% @events.each do |e| %>
plotPosition('<%= e.longitude %>','<%= e.latitude %>');
<% end %>
} else {
alert("Canvas not supported!");
}
}
所以我的想法是plotPosition函数是绘制每个坐标,但每次给它一个新坐标时,旧的坐标被删除/移动并替换为新坐标。可能是一个简单的解决方案,但我已经在这几个小时,但无济于事。砰的一声。
关于问题的任何想法?
答案 0 :(得分:0)
从代码示例来看,你似乎也在清除背景 - 你没有显示对这些方法的调用,但我会假设你在代码中的其他地方绘制新点(?)之前这样做
如果是的话 -
在清除画布之前,您需要重绘所有您绘制的点。
执行此操作的一种方法是将已有的点存储在数组中,然后调用重绘函数来绘制其中的所有内容。或者将服务器上的点直接存储到具有转换值的数组中,并且当所有点都已转换后重绘所有内容。
基于后一种方法的简化示例(需要进行一些重新分解):
/// GLOBALS (put ctx here instead as well..)
var points = [],
canvas = document.getElementById('map'),
ctx = canvas.getContext ? canvas.getContext('2d') : null;
if (ctx === null) {...sorry...};
...
/// somewhere comes the logic to get the points themselves.
...
<% @events.each do |e| %>
storePosition('<%= e.longitude %>','<%= e.latitude %>');
<% end %>
...
/// after new points are added, render them all
renderAll();
function storePosition(long, lat) {
points.push{
x: degreesOfLongitudeToScreenX(long)
y: degreesOfLatitudeToScreenY(lat),
long: long,
lat: lat
}
}
function renderAll();
/// clear and redraw background of canvas
drawBackground(ctx);
// Draw the map background
drawMapBackground(ctx);
// Draw the map background
// drawGraticule(ctx);
// Draw the land
drawLandMass(ctx);
/// now plot all the stored points
ctx.fillStyle = 'rgb(0,0,0)';
for(var i = 0, point; point = points[i]; i++) {
ctx.beginPath();
ctx.arc(
point.x,
point.y,
5,
0,
2 * Math.PI
);
ctx.closePath();
ctx.fill();
}
}
你可以实现对x和y的检查,看看它们是否在画布中,但这绝对没有必要,因为画布会为你剪辑它们,内部剪辑比JavaScript更快地进行检查。但是出于调试目的,如果您怀疑这一点,您可以随时进行检查。但是你写的是绘制了点,但是当绘制一个新点时会被删除,所以我认为这不是问题所在。