Dan*_*her 24 jquery drawing ruby-on-rails lines
我想在图像上画线.基本上允许用户绘制他们喜欢的山路的路径.
1)有没有人知道一个很好的简单库来绘制基本线?
2)用户在图像上绘制一堆线后,将数据保存到数据库的最佳方法是什么?
这是一个使用canvas元素和常规js(无库)的快速解决方案,可以帮助您入门.
将canvas元素添加到html页面.
<canvas id="canvas" width="800" height="600">
Your browser does not support the canvas element.
</canvas>
Run Code Online (Sandbox Code Playgroud)
添加javascript以在画布上绘制图像.然后它会监听点击次数,并在用户点击时绘制线条.
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = document.getElementById('canvas').getContext('2d');
var points = [];
// Determine where the user clicked, I believe I pulled this from elsewhere on StackOverflow a while ago.
function getCursorPosition(e) {
var mx, my;
if (e.pageX || e.pageY) {
mx = e.pageX;
my = e.pageY;
}
else {
mx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
my = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
mx -= canvas.offsetLeft;
my -= canvas.offsetTop;
return {x: mx, y: my};
}
// Once we have at least two points, draw a line between them.
function drawPath() {
context.beginPath();
for (var i = 0; i < points.length - 1; i++) {
context.moveTo(points[i]['x'], points[i]['y']);
context.lineTo(points[i+1]['x'], points[i+1]['y']);
context.stroke();
}
context.closePath();
}
// Listen for clicks, and redraw the map when they occur.
function initPointCollection() {
canvas.onclick = function(e) {
var point = getCursorPosition(e);
points.push(point);
if (points.length > 1) {
drawPath();
}
}
}
function init() {
// Load up your image. Don't attempt to draw it until we know it's been loaded.
var mountain = new Image();
mountain.onload = function() {
context.drawImage(this, 0, 0);
initPointCollection();
}
mountain.src = 'mountain.png'; // Replace with actual image.
}
// Should check if document has finished loading first, but I'm too lazy, especially without JQuery.
init();
</script>
Run Code Online (Sandbox Code Playgroud)
实现我忘了回答问题的后半部分,关于将图像保存到Rails DB.这很难回答,因为它取决于您想对结果数据做什么.如果您只想要最终图像,我建议您将图像保存到文件系统(我使用S3存储我的所有图像).有关如何在StackOverflow上执行此操作的讨论:将HTML Canvas捕获为gif/jpg/png/pdf?
如果您需要操纵绘制的路径,我会保存单个数据点以及对底层图像的引用.通过ajax将数据点发送回Rails服务器,以及图像的URL.您的数据库表可能看起来像这样:
create_table :hiking_paths do |t|
t.string 'image_url', :null => false
t.string 'points', :limit => 1000 #if you want unlimited points, change to text column type
t.timestamps
end
Run Code Online (Sandbox Code Playgroud)