Javascript 如何制作可移动的?
我有个问题。如何创建一个可移动的图像并将其移动到图像上? 我考虑过改变参数边距,但我不知道如何在图像上放置边距 如果可以,请帮助我。回答基于: CSS HTMLJavascript 如何制作可移动的?,javascript,css,html,Javascript,Css,Html,我有个问题。如何创建一个可移动的图像并将其移动到图像上? 我考虑过改变参数边距,但我不知道如何在图像上放置边距 如果可以,请帮助我。回答基于: CSS HTML 你为什么要这么做 你想在图像中画一条线,对吗?为什么不使用画布呢?下面是一个例子: 每次在画布中单击或拖动时,您只需重新绘制该行。请使用与在图像上覆盖任何其他html相同的方式修改代码。需要确定imageWelcome to stackoverflow@kipill在父容器中的绝对位置,stackoverflow采用规则来鼓励可维护的问
你为什么要这么做 你想在图像中画一条线,对吗?为什么不使用画布呢?下面是一个例子:
每次在画布中单击或拖动时,您只需重新绘制该行。请使用与在图像上覆盖任何其他html相同的方式修改代码。需要确定imageWelcome to stackoverflow@kipill在父容器中的绝对位置,stackoverflow采用规则来鼓励可维护的问题和答案,这些问题和答案会持续很长时间。一个好的开始是发布你自己的坏代码,我们可以尝试帮助你。请务必阅读上面chazsolo的链接。谢谢。我考虑过canvas,但之前没有看到这个示例。我这样做是因为我有能力移动这条线。谢谢你的回答
#draggable-hr {
cursor:move;
position: absolute;
width: 100%;
}
<hr id="draggable-hr">
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-hr').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
Original image:
<br>
<br>
<img id="scream" width="220" height="277" src="http://www.w3schools.com/tags/img_the_scream.jpg" alt="The Scream">
<br> Canvas:
<br>
<br>
<canvas id="myCanvas" width="320" height="277"></canvas>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 50, 0);
ctx.beginPath();
ctx.moveTo(0, 138);
ctx.lineTo(320, 138);
ctx.stroke();