-1

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;" />
fewaf
  • 145
  • 13

1 Answers1

1

You can use two canvas elements instead:

(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:

Fancy image

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

Community
  • 1
  • 1
  • this was great, thanks a lot! you made it very easily understandable, I really appreciate it. – fewaf Feb 19 '14 at 23:32
  • So this worked perfectly, the only thing is that when I add the image, the image is very large. I can't figure out how to scale it... just setting img.width = 200 doesn't do anything. Any ideas? – fewaf Feb 20 '14 at 01:50
  • @user3285918 you can use the extended parameters of drawImage like for example: `ctxMouse.drawImage(0, 0, canvas.width, canvas.height);` –  Feb 20 '14 at 01:55