I have a drawing pad, and want to overlay an image that is just an outline (so the image is transparent except for some black lines).

为君一笑 提交于 2019-12-13 08:08:50

问题


I have it so that you can draw under the image, but you must start drawing outside of the image border and move under the image. So you can't start right on the image. How do I fix this?

My html is just:

<canvas id="canvas"></canvas>

<img id="html5" src="http://i.imgur.com/Wpx3Vum.png" style="position:absolute;left:100px;top:15px;" />

回答1:


You can use two canvas elements instead:

  • Put two canvas elements on top of each other
  • Draw the image you want to superimpose on the top canvas
  • Add mouse event listener to the top canvas
  • When drawing read the positions from top canvas but draw the lines to the bottom one using the bottom canvas' context

(links just meant as examples)

An example of this could be including a simple basic draw function:

Online demo

HTML:

<div id="cont">
    <canvas id="canvasBottom" width=400 height=400></canvas>
    <canvas id="canvasTop" width=400 height=400></canvas>
</div>

CSS:

#cont {
    position:relative;
    border:1px solid #777;
    height:400px;
    }
#cont > canvas {
    position:absolute;
    left:0;
    top:0;
    cursor:crosshair;
    }

JavaScript:

Load and set the image to top layer:

var img = new Image,
    canvas = document.getElementById('canvasBottom'),
    canvasTop = document.getElementById('canvasTop'),
    ctx = canvas.getContext('2d'),
    ctxMouse = canvasTop.getContext('2d');

img.onload = setup;
img.src = 'http://i.imgur.com/HNiER0v.png';

ctx.lineWidth = 5;
ctx.strokeStyle = 'rgb(0, 100, 255)';

function setup() {
    ctxMouse.drawImage(this, 0, 0);
}

Handle mouse:

var px, py, isDown = false;

canvasTop.onmousedown = function (e) {
    var pos = getXY(e);
    px = pos.x;
    py = pos.y;
    isDown = true;
}

canvasTop.onmouseup = function () {
    isDown = false;
}

canvasTop.onmousemove = function (e) {
    if (isDown) {
        var pos = getXY(e);
        ctx.beginPath();
        ctx.moveTo(px, py);
        ctx.lineTo(pos.x, pos.y);
        ctx.stroke();
        px = pos.x;
        py = pos.y;
    }
}

function getXY(e) {
    var rect = canvasTop.getBoundingClientRect();
    return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
    };
}

As you can see you can now draw behind the initial drawing:

(Now, if that is not a master piece than I don't know what a master piece is..!)



来源:https://stackoverflow.com/questions/21890472/i-have-a-drawing-pad-and-want-to-overlay-an-image-that-is-just-an-outline-so-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!