问题描述
在HTML5 Canvas中,最简单的方法是在图像上绘制并移动一条线(已在画布上),保留下面的图像? (例如,有一条垂直线跟踪鼠标X的位置)
In HTML5 Canvas, what's the simplest way to draw and move a line over an Image (already on the canvas), preserving the image underneath? (e.g. have a vertical line track the mouse X position)
我当前的画布:
$(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);
});
P.S。我正在与你的Facebook网络竞争。愿最好的Lazyweb获胜(我的谢意):)
P.S. I'm racing you against my Facebook network. May the best Lazyweb win (my gratitude) :)
推荐答案
你将不得不用帆布做大部分的基础工作在这种情况下,您将必须实现移动行的功能,然后重绘所有内容。
You will have to do most of the ground-work with canvas which in this case you will have to implement the functionality to move the line and then redraw everything.
步骤可以是:
- 将该行保留为可自我渲染的对象(对象上的方法)
- 收听mousemove(在本例中)以便移动线
- 对于每次移动,重绘背景(图像)然后将线条渲染到新位置
你可以整体重绘背景,或者你可以优化它以只画最后一行。
You can redraw the background as a whole or you can optimize it to just draw over the last line.
这是一个示例代码和一个 :
Here is some example code of this and a live demo here:
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;
}
现在我们需要做的就是有机会来更新背景和每次移动的行:
Now all we need to do is to have a mechnism to update the background and the line for each move:
/// 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();
}
自定义行对象在此演示中非常简单:
The custom line object is in this demo very simple:
/// 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将其设置为背景图像。在重新绘制直线之前,您仍需要清除画布。
If you are not gonna do anything specific with the image itself you can also set it as a background-image using CSS. You will still need to clear the canvas before redrawing the line though.
这篇关于在保留图像的同时在HTML5 Canvas中绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!