In this tutorial we are going to see how to draw rectangle over image
using mouse events.
Step 2: Create a Html page and paste the following code inside the
body tag.
Step 3: create a css/Styles.css file and paste the following code.
$(document).ready(function () {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var rect = {};
var drag = false;
var imageObj = null;
var rotateflag = true;
var degree = 0;
function init() {
imageObj = new Image();
imageObj.onload = function () { ctx.drawImage(imageObj,imageObj.width/2,imageObj.width/2); };
imageObj.src = 'img/forest.jpg';
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseUp() { drag = false; }
function mouseMove(e) {
if (drag) {
if(rotateflag)
{
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(imageObj,imageObj.width/2,imageObj.width/2);
}
else{
drawRotated(degree);
}
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY;
ctx.strokeStyle = 'red';
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
}
}
init();
function drawRotated(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(degrees*Math.PI/180);
// draw it up and to the left by half the width
// and height of the image
ctx.drawImage(imageObj,-imageObj.width/2,-imageObj.width/2);
ctx.restore();
}
$("#Rotate").click(function(){
rotateflag = false;
degree = degree + 90;
if(degree > 270)
{
degree = 0;
rotateflag = true;
}
console.log('degree:'+degree);
drawRotated(degree);
});
});
No comments:
Post a Comment