我想要一张汽车的图像,当用户单击汽车上的某个点时,我会在该点上放置一个 x 图像或圆形图像。我需要保存他们点击的位置,以便当他们回来时我将其显示在同一位置。
在 html 中执行此操作的最佳方法是什么?
我应该使用一张图像并在其上叠加其他图像吗?
我应该使用 html5 吗?
有人知道类似性质的工作示例吗?
想要使用js、html5等来使其在iphone safari(不是 native 应用程序)上工作。应用程序是 ruby on Rails,因此我可以利用一些服务器端功能,但如果可能的话,我更愿意在 html/css 中利用尽可能多的功能。
最佳答案
您可以使用 canvas
元素来执行此操作。 canvas
元素允许您在其中绘制图像和形状。
要存储和检索点击,您可以使用网络存储 (localStorage
)。
例如 - 加载图像并将其绘制到 Canvas 上:
<强> ONLINE DEMO HERE
HTML:
<canvas id="demo" width="500" height="400"></canvas>
JavaScript:
/// get context for canvas, cache dimension
var ctx = demo.getContext('2d'),
w = demo.width,
h = demo.height,
img = new Image(); /// the image we want to load
/// when done go draw existing marks and start listening for clicks
img.onload = function() {
renderMarks();
demo.onclick = function(e) {
/// convert mouse coord relative to canvas
var rect = demo.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
/// store mark
addMark(x, y);
/// redraw everything
renderMarks();
}
}
这些是主要功能,这首先将现有标记渲染到图像顶部的 Canvas 上:
function renderMarks() {
/// re-draw image which also serves to clear canvas
ctx.drawImage(img, 0, 0, w, h);
/// get existing marks from localStorage
var marks = localStorage.getItem('marks'),
i = 0;
/// if any, render them all
if (marks !== null) {
/// localStorage can only store strings
marks = JSON.parse(marks);
/// set color and line width of circle
ctx.strokeStyle = '#f00';
ctx.lineWidth = 3;
/// iterate marks and draw each one
for(;i < marks.length; i++) {
ctx.beginPath();
ctx.arc(marks[i][0], marks[i][1], 30, 0, 2 * Math.PI);
ctx.stroke();
}
}
}
这会向集合添加一个标记:
function addMark(x, y) {
/// get existing marks or initialize
var marks = JSON.parse(localStorage.getItem('marks') || '[]');
/// add mark
marks.push([x, y]);
/// update storage
localStorage.setItem('marks', JSON.stringify(marks));
}
(代码可以通过多种方式进行优化,但我这样做是为了展示基本原理)。
如果您现在离开该页面并返回,您将看到标记再次呈现(免责声明:jsfiddle 可能会或可能不会提供相同的页面,因此请在本地/“真实”页面中进行测试以确保)。
这里的圆圈可以是任何东西,图像,不同的形状等等。
要清除标记,只需调用:
localStorage.clear();
或者如果您还存储其他数据:
localStorage.removeItem('marks');
关于javascript - 如何允许用户将图像放在 html 中的另一个图像之上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18730566/