On html page which has some draggable images we have to draw shapes or lines using mouse pointer, drawing images and shapes is done, but not on draggable images .Also, if user moves the image the shape drawn earlier should remain
their. Meanwhile, i have been able to create the shapes and draw lines but when i try to draw line
over image it goes back into the background. Can someone suggest how can i achieve the same using
canvas and html5, which is being currently used as well.
One method is to create a function that draws both your image and the shapes associated with that image
You can keep the image and its shapes coordinated by drawing the shape with the same offset as the image offset. So if you draw the image at [x,y] then you would add x & y to each point in the shape:
// points[] is an array of points that defines the shape you
// want drawn on your image
function drawImageWithShapes(img,points,x,y){
ctx.drawImage(img,x,y);
ctx.beginPath();
ctx.moveTo(points[0].x+x,points[0].y+y);
for(var i=1; i<points.length;i++){
ctx.lineTo(points[i].x+x,points[i].y+y);
}
ctx.stroke();
}
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.lineWidth=4;
ctx.strokeStyle='red';
var x=50;
var y=50;
var points=[];
points.push({x:37,y:0});
points.push({x:75,y:75});
points.push({x:0,y:75});
points.push({x:37,y:0});
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start(){
drawImageWithShapes(img,points,x,y);
}
function drawImageWithShapes(img,points,x,y){
ctx.drawImage(img,x,y);
ctx.beginPath();
ctx.moveTo(points[0].x+x,points[0].y+y);
for(var i=1; i<points.length;i++){
ctx.lineTo(points[i].x+x,points[i].y+y);
}
ctx.stroke();
}
$('#test').click(function(){
x+=10;
y+=10;
ctx.clearRect(0,0,cw,ch);
drawImageWithShapes(img,points,x,y);
});
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id=test>Move and Redraw</button><br><br>
<canvas id="canvas" width=300 height=300></canvas>