在HTML5 Canvas中,最简单的方法是在图像(已经在画布上)上绘制和移动一条线,并在其下保留图像?(例如,一条垂直线跟踪鼠标X的位置)
我当前的画布:
$(document).ready(function() {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0,0);
}
imageObj.src = "http://example.com/some_image.png";
$('#myCanvas').click(doSomething);
});
附言:我正在与您对抗我的Facebook网络。愿最好的Lazyweb获胜(我的感激):)
您将必须使用画布完成大部分基础工作,在这种情况下,您将必须实现功能来移动线条,然后重新绘制所有内容。
步骤可以是:
您可以整体重绘背景,也可以对其进行优化以仅绘制最后一行。
这是一些示例代码,还有一个现场演示:
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将其设置为背景图像。但是,您仍然需要在重新绘制线条之前清除画布。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句