在保留图像的同时在HTML5 Canvas中绘制图像

Asa*_*tov 8 javascript html5 drawing canvas

在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);
});
Run Code Online (Sandbox Code Playgroud)

PS我正在与你的Facebook网络竞争.愿最好的Lazyweb获胜(我的谢意):)

小智 15

你将不得不用canvas进行大部分的基础工作,在这种情况下你必须实现移动线然后重绘所有内容的功能.

步骤可以是:

  • 将该行保持为可以自我渲染的对象(对象上的方法)
  • 听取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;
}
Run Code Online (Sandbox Code Playgroud)

现在我们需要做的就是有机制来更新每个动作的背景和线条:

/// 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();
}
Run Code Online (Sandbox Code Playgroud)

自定义行对象在此演示中非常简单:

/// 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你不打算对图像本身做任何特定的事情,你也可以使用CSS将它设置为背景图像.在重新绘制线之前,您仍需要清除画布.


Shi*_*mae 5

可能这不是一个实际的答案,以防万一您需要它(将来)。如果使用一些库,使用画布会更好(也更容易)。我尝试过 CreateJS 的 EaselJS 并且发现自己很喜欢它。你可以看看EaselJS (我很早以前就做过一个允许使用EaselJS绘制和拖动图像的例子)