您必须使用画布完成大部分基础工作,在这种情况下,您必须实现移动线条然后重绘所有内容的功能。
步骤可以是:
- 将线条保持为可以自渲染的对象(对象上的方法)
- 听mousemove(在这种情况下)以移动行
- 对于每次移动,重绘背景(图像),然后在新位置渲染线条
您可以重新绘制整个背景,也可以对其进行优化以仅绘制最后一行。
这是一些示例代码和现场演示:
var canvas = document.getElementById('demo'), /// canvas element
ctx = canvas.getContext('2d'), /// context
line = new Line(ctx), /// our custom line object
img = new Image; /// the image for bg
ctx.strokeStyle = '#fff'; /// white line for demo
/// start image loading, when done draw and setup
img.onload = start;
img.src = 'http://i.imgur.com/O712qpO.jpg';
function start() {
/// initial draw of image
ctx.drawImage(img, 0, 0, demo.width, demo.height);
/// listen to mouse move (or use jQuery on('mousemove') instead)
canvas.onmousemove = updateLine;
}
现在我们需要做的就是有一个机制来更新每个动作的背景和线条:
/// updates the line on each mouse move
function updateLine(e) {
/// correct mouse position so it's relative to canvas
var r = canvas.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top;
/// draw background image to clear previous line
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
/// update line object and draw it
line.x1 = x;
line.y1 = 0;
line.x2 = x;
line.y2 = canvas.height;
line.draw();
}
自定义线对象在这个演示中非常简单:
/// This lets us define a custom line object which self-draws
function Line(ctx) {
var me = this;
this.x1 = 0;
this.x2 = 0;
this.y1 = 0;
this.y2 = 0;
/// call this method to update line
this.draw = function() {
ctx.beginPath();
ctx.moveTo(me.x1, me.y1);
ctx.lineTo(me.x2, me.y2);
ctx.stroke();
}
}
如果您不打算对图像本身做任何特定的事情,您也可以使用 CSS 将其设置为背景图像。不过,在重新绘制线条之前,您仍然需要清除画布。