Draw parallelogram on canvas - javascript

There are so many examples to draw rectangles with mouse on canvas. For example, check this jsFiddle. Is it possible to draw parallelogram?
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function(e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function(e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
#canvas {
width: 2000px;
height: 2000px;
border: 10px solid transparent;
}
.rectangle {
border: 1px solid #FF0000;
position: absolute;
}
<div id="canvas"></div>
I think this question is self explanatory.

Related

Draggable text box scales more than expected

I made a text box and boxes on the corners for resizing. The first time I drag, it works perfectly fine, but after the 1st time, the dragging amount seems to multiply. (Don't mind the position of the dragging nodes). If you drag once, it scales fine with the mouse. It seems as if every time after that, when you drag, it scales farther and farther from the user's mouse, causing an 'uncontrollable' scale. I reset the values of the prevX and prevY values at the end of the move function. I'm not sure if that's the issue though. The issue, I believe, is with the scaling with getBoundingClientRect() in the resize portion. Moving the textbox, however, works perfectly fine. Here is my code:
var textBox = document.querySelector(".text-box");
var textArea = document.querySelector('.text-field');
textArea.focused = false;
textBox.addEventListener('mousedown', mousedown);
let isResizing = false;
let isTyping = false;
textArea.addEventListener('dblclick', type)
function type(){
if (!isTyping){
isTyping = true;
textArea.style.cursor = 'text';
}else {
isTyping = false;
textArea.style.cursor = 'default';
}
}
document.body.onclick = function(e){
if (e.target != textArea){
isTyping = false;
e.target.style.cursor = 'default';
}
}
function mousedown(e){
if (e.target == textArea){
e.target.style.cursor = 'default';
}
window.addEventListener('mousemove', mousemove);
window.addEventListener('mouseup', mouseup);
let prevX = e.clientX;
let prevY = e.clientY;
function mousemove(e){
if(!isResizing && !isTyping){
let newX = prevX - e.clientX;
let newY = prevY - e.clientY;
const rect = textBox.getBoundingClientRect();
textBox.style.left = rect.left - newX + "px";
textBox.style.top = rect.top - newY + "px";
prevX = e.clientX;
prevY = e.clientY;
}
}
function mouseup(){
window.removeEventListener('mousemove', mousemove);
window.removeEventListener('mouseup', mouseup);
}
const handles = document.querySelectorAll('.handle');
let currentHandle;
for(let handle of handles){
handle.addEventListener('mousedown', mousedown);
function mousedown(e){
currentHandle = e.target;
isResizing = true;
let prevX = e.clientX;
let prevY = e.clientY;
window.addEventListener('mousemove', mousemove);
window.addEventListener('mouseup', mouseup);
function mousemove(e){
const rect = textBox.getBoundingClientRect();
if (currentHandle.classList.contains("se")) {
textBox.style.width = rect.width - (prevX - e.clientX) + "px";
textBox.style.height = rect.height - (prevY - e.clientY) + "px";
} else if (currentHandle.classList.contains("sw")) {
textBox.style.width = rect.width + (prevX - e.clientX) + "px";
textBox.style.height = rect.height - (prevY - e.clientY) + "px";
textBox.style.left = rect.left - (prevX - e.clientX) + "px";
} else if (currentHandle.classList.contains("ne")) {
textBox.style.width = rect.width - (prevX - e.clientX) + "px";
textBox.style.height = rect.height + (prevY - e.clientY) + "px";
textBox.style.top = rect.top - (prevY - e.clientY) + "px";
} else {
textBox.style.width = rect.width + (prevX - e.clientX) + "px";
textBox.style.height = rect.height + (prevY - e.clientY) + "px";
textBox.style.top = rect.top - (prevY - e.clientY) + "px";
textBox.style.left = rect.left - (prevX - e.clientX) + "px";
}
prevX = e.clientX;
prevY = e.clientY;
}
function mouseup(){
window.removeEventListener('mousemove', mousemove);
window.removeEventListener('mouseup', mouseup);
textArea.focused = false;
isResizing = false;
}
}
}
}
.text-box{
height: 50px;
width: 150px;
position: absolute;
}
.handle{
position: absolute;
width: 5px;
height: 5px;
background-color: blue;
z-index: 2;
}
.ne{
top: -1px;
right: -1px;
cursor: ne-resize;
}
.nw{
top: -1px;
left: -1px;
cursor: nw-resize;
}
.sw{
bottom: -1px;
left: -1px;
cursor: sw-resize;
}
.se{
bottom: -1px;
right: -1px;
cursor: se-resize;
}
.text-field {
width: 100%;
height: 100%;
resize: none;
cursor: default;
}
<div class="text-box">
<textarea class="text-field">Click to add text...</textarea>
<div class="handle ne"></div>
<div class="handle nw"></div>
<div class="handle sw"></div>
<div class="handle se"></div>
</div>
It is just as Chris said on the comment, (However I tried many things before understanding the issue...)
One way very simple to solve it is to take out your for loop from inside your mousedown function.
var textBox = document.querySelector(".text-box");
var textArea = document.querySelector('.text-field');
textArea.focused = false;
textBox.addEventListener('mousedown', mousedown);
let isResizing = false;
let isTyping = false;
textArea.addEventListener('dblclick', type)
function type(){
if (!isTyping){
isTyping = true;
textArea.style.cursor = 'text';
}else {
isTyping = false;
textArea.style.cursor = 'default';
}
}
document.body.onclick = function(e){
if (e.target != textArea){
isTyping = false;
e.target.style.cursor = 'default';
}
}
function mousedown(e){
if (e.target == textArea){
e.target.style.cursor = 'default';
}
window.addEventListener('mousemove', mousemove);
window.addEventListener('mouseup', mouseup);
let prevX = e.clientX;
let prevY = e.clientY;
function mousemove(e){
if(!isResizing && !isTyping){
let newX = prevX - e.clientX;
let newY = prevY - e.clientY;
const rect = textBox.getBoundingClientRect();
textBox.style.left = rect.left - newX + "px";
textBox.style.top = rect.top - newY + "px";
prevX = e.clientX;
prevY = e.clientY;
}
}
function mouseup(){
window.removeEventListener('mousemove', mousemove);
window.removeEventListener('mouseup', mouseup);
}
}
const handles = document.querySelectorAll('.handle');
let currentHandle;
for(let handle of handles){
handle.addEventListener('mousedown', mousedown);
function mousedown(e){
currentHandle = e.target;
isResizing = true;
let prevX = e.clientX;
let prevY = e.clientY;
window.addEventListener('mousemove', mousemove);
window.addEventListener('mouseup', mouseup);
function mousemove(e){
const rect = textBox.getBoundingClientRect();
if (currentHandle.classList.contains("se")) {
textBox.style.width = rect.width - (prevX - e.clientX) + "px";
textBox.style.height = rect.height - (prevY - e.clientY) + "px";
} else if (currentHandle.classList.contains("sw")) {
textBox.style.width = rect.width + (prevX - e.clientX) + "px";
textBox.style.height = rect.height - (prevY - e.clientY) + "px";
textBox.style.left = rect.left - (prevX - e.clientX) + "px";
} else if (currentHandle.classList.contains("ne")) {
textBox.style.width = rect.width - (prevX - e.clientX) + "px";
textBox.style.height = rect.height + (prevY - e.clientY) + "px";
textBox.style.top = rect.top - (prevY - e.clientY) + "px";
} else {
textBox.style.width = rect.width + (prevX - e.clientX) + "px";
textBox.style.height = rect.height + (prevY - e.clientY) + "px";
textBox.style.top = rect.top - (prevY - e.clientY) + "px";
textBox.style.left = rect.left - (prevX - e.clientX) + "px";
}
prevX = e.clientX;
prevY = e.clientY;
}
function mouseup(){
window.removeEventListener('mousemove', mousemove);
window.removeEventListener('mouseup', mouseup);
textArea.focused = false;
isResizing = false;
}
}
}
Just one more thing, I added these lines to your code, to not remove the resize cursor when clicking the handler:
document.body.onclick = function(e){
if (e.target != textArea){
if(e.target.classList.contains('handle')){
isTyping = false
}
else{
isTyping = false;
e.target.style.cursor = 'default';
}
}
}

Draw on canvas with vue

I want to adapt a selection with rectangle (made with JS and html) in VueJs.
I have this version:
https://codepen.io/sebastiancz/pen/mdJVJRw
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
console.log(mouse.x, mouse.y)
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onmousedown = function (e) {
console.log("Start.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
}
canvas.onmouseup = function (e) {
element = null;
// canvas.ctx.clearRect();
console.log("finsihed.");
}
}
and this is my non working version version in vue :
https://codepen.io/sebastiancz/pen/mdJPvOP?editors=0011
How can I fix this ?
Here is something that you can do with Vue.js and HTML5 Canvas. You can further expand this to show previous selections by creating an array and storing start and end positions of the selections.
Vue.component("selection", {
template: `<canvas id='canvas' ref='select' #mousedown='startSelect' #mousemove='drawRect' #mouseup='stopSelect'></canvas>`,
data() {
return {
ctx: null,
selectionMode: false,
startPosition: {
x: null,
y: null
}
};
},
methods: {
startSelect(e) {
this.selectionMode = true;
this.startPosition.x = e.clientX;
this.startPosition.y = e.clientY;
},
drawRect(e) {
if (this.selectionMode) {
console.log(this.startPosition);
this.ctx.beginPath();
this.ctx.rect(
this.startPosition.x,
this.startPosition.y,
e.clientX - this.startPosition.x,
e.clientY - this.startPosition.y
);
this.ctx.closePath();
this.ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
this.ctx.strokeStyle = "#f00";
this.ctx.stroke();
}
},
stopSelect(e) {
this.ctx.fillStyle = "#fff";
this.selectionMode = false;
this.startPosition.x = null;
this.startPosition.y = null;
}
},
mounted() {
this.$refs.select.height = window.innerHeight;
this.$refs.select.width = window.innerWidth;
this.ctx = this.$refs.select.getContext("2d");
// this.ctx.fillRect(0,0,500,500);
}
});
new Vue({
el: "#app",
data: {
hello: "world"
}
});
body {
margin: 2rem;
background: #eee;
}
#canvas {
background: white;
box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.2);
}
<div id="app">
<selection></selection>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Not being able to draw over canvas html5

I am trying to draw a rectangle on a canvas in HTML5. If I use a canvas (with fileList as id) it is not getting displayed on the screen but if I used a div it is getting displayed. I want to display a rectangle over an image for annotation.
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event;
if (ev.pageX) {
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) {
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "crosshair";
console.log("finsihed.");
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle';
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
initDraw(document.getElementById('fileList'));
.rectangle {
border: 10px solid black;
position: absolute;
background-color: black;
}
<canvas id="fileList" height="680px" width="800px"></canvas>
Summary
You seem to be asking how to overlap a DIV on a canvas.
Answer
Using your CSS, use the Z-Index to control how the layers overlap
You will need to set one as Z-Index:0 and the DIV with Z-Index: of 1 or above;
Don't forget: that DIV elements without a height or width will not show show in Internet Explorer or Safari, so ensure your CSS includes a height and width
function funStart(){
if (typeof(document.getElementById("fileList").getContext("2d")) == undefined){
console.log ("No HTML5 Canvas support");
return;
}else{
var ctx = document.getElementById("fileList").getContext("2d");
}
ctx.canvas.height = 500;
ctx.canvas.width = 500;
ctx.fillStyle = "#F00";
ctx.fillRect (0,0, ctx.canvas.width, ctx.canvas.height);
ctx.fill();
}
document.addEventListener("DOMContentLoaded", funStart(), false);
.rectangle {
border: 10px solid silver;
color: white;
height: 300px;
width: 200px;
position: absolute;
top: 10;
left: 10;
background-color: black;
z-index: 23;
}
canvas{
position: absolute;
z-index: 0;
}
<canvas id="fileList" height="680px" width="800px"></canvas>
<div id="messageBoard" class="rectangle">My DIV Message goes here</div>
You're putting the .rectangle <div> inside the <canvas>, but the children of <canvas> are used as fallback content. They'll only be displayed if the browser doesn't support <canvas>.
Instead, wrap the <canvas> in a positioned element to create a manageable containing block, and add the .rectangles to that element:
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event;
mouse.x = ev.offsetX;
mouse.y = ev.offsetY;
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "crosshair";
console.log("finsihed.");
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle';
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.closest('.canvaswrap').appendChild(element);
canvas.style.cursor = "crosshair";
}
}
}
initDraw(document.getElementById('fileList'));
.rectangle {
border: 10px solid black;
position: absolute;
background-color: black;
box-sizing: border-box;
pointer-events: none;
}
.canvaswrap {
position: relative;
padding: 0;
}
<div class="canvaswrap">
<canvas id="fileList" height="680" width="800"></canvas>
</div>
(Since we're now positioning relative to an element instead of the entire page, I changed your setMousePosition logic as well. I also added box-sizing: border-box; to the .rectangles' styling so that they're not off the clicked coordinates by 10px, and pointer-events: none; so mouse events get sent to the <canvas> instead of being caught by overlaid .rectangles. And <canvas>'s height and width attributes are defined to be in pixels; you don't need to put the "px" in them.)

Move element with mouse starts to snap up and down

I am trying to make a drag on y axis functionality using mousedown, mousemove events. The formula is as follows:
var position = e.clientY - getOrigin(myDiv).top;
myDiv.style.transform = 'translate3d(0px, ' + position + 'px, 0px)';
function getOrigin(elm) {
...
return {
left: box.left + (win.pageXOffset || docElem.scrollLeft) - clientLeft,
top: box.top + (win.pageYOffset || docElem.scrollTop) - clientTop
};
}
When I drag the element, it snaps up and down really fast. Why is that happening, and how can I fix it?
JSFiddle
var myDiv = document.getElementById('myDiv');
myDiv.addEventListener('mousedown', handleMouseDown);
window.addEventListener('mouseup', handleMouseUp);
function handleMouseDown(e) {
window.addEventListener('mousemove', handleMouseMove);
}
function handleMouseUp(e) {
window.removeEventListener('mousemove', handleMouseMove);
}
function handleMouseMove(e) {
e.preventDefault();
var position = e.clientY - getOrigin(myDiv).top;
myDiv.style.transform = 'translate3d(0px, ' + position + 'px, 0px)';
}
function getOrigin(elm) {
var box = (elm.getBoundingClientRect) ? elm.getBoundingClientRect() : {
top: 0,
left: 0
},
doc = elm && elm.ownerDocument,
body = doc.body,
win = doc.defaultView || doc.parentWindow || window,
docElem = doc.documentElement || body.parentNode,
clientTop = docElem.clientTop || body.clientTop || 0, // border on html or body or both
clientLeft = docElem.clientLeft || body.clientLeft || 0;
return {
left: box.left + (win.pageXOffset || docElem.scrollLeft) - clientLeft,
top: box.top + (win.pageYOffset || docElem.scrollTop) - clientTop
};
}
body {
margin-top: 50px;
padding-top: 50px;
}
#myDiv {
background-color: orange;
width: 200px;
height: 100px;
}
<div id="myDiv"></div>
Because I couldn't exactly figure out what was causing the problem in OPs question (for an unknown reason box.top was returning 2 different values alternately on each pixel movement in OPs script), I've written a different script that works perfectly fine:
//document.addEventListener('DOMContentLoaded', function(){
var myDiv = document.getElementById('myDiv');
myDiv.addEventListener('mousedown', handleMouseDown);
window.addEventListener('mouseup', handleMouseUp);
function handleMouseDown(e) {
window.addEventListener('mousemove', mouseMove.start(this, 'body',e));
}
function handleMouseUp(e) {
window.removeEventListener('mousemove', mouseMove.stop('body'));
}
var mouseMove = function(){
return {
move: function(elm, posY){
elm.style.top = posY + "px";
},
start: function(elm, container, e){
e = e || window.event;
var posY = e.clientY,
elmTop = elm.style.top,
elmHeight = parseInt(elm.style.height),
conHeight = parseInt(document.getElementById(container).style.height);
elmTop = elmTop.replace('px','');
var diffY = posY - elmTop;
document.onmousemove = function(e){
e = e || window.event;
var posY = e.clientY,
Y = posY - diffY;
if (Y < 0) Y = 0;
if (Y + elmHeight > conHeight) Y = conHeight - elmHeight;
mouseMove.move(elm,Y);
}
},
stop : function(container){
var a = document.createElement('script');
document.onmousemove = function(){}
},
}
}();
//});
#body {
margin-top: 50px;
position: absolute;
}
#myDiv {
position: absolute;
background-color: orange;
width: 200px;
height: 100px;
}
<div id="body">
<div id="myDiv"></div>
</div>

Capture user input on HTML canvas/Javascript and vice versa

I am trying to draw a rectangle in HTML5 canvas based on user input. I am also trying to do the opposite. If a user draws a rectangle in the canvas, the width and height values are dropped into the form. Please see my jsfiddle.
http://jsfiddle.net/hbrennan72/FyTx5/
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var rect = {};
//var drag = false;
function getarea()
{
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var perim = wid * 2 + hgt * 2;
if (wid =="") {
document.getElementById("errors").innerHTML = "The value for the width is blank.";
document.getElementById('wid').focus();
}
else if (hgt == "") {
document.getElementById("errors").innerHTML = "The value for the height is blank.";
document.getElementById("hgt").focus();
}
else if (isNaN (wid)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the width.";
document.getElementById('wid').focus();
}
else if (isNaN (hgt)) {
document.getElementById("errors").innerHTML = "Please enter a numeric value for the height.";
document.getElementById("hgt").focus();
}
else if (wid <= 0) {
document.getElementById("errors").innerHTML = "The width is less than or equal to zero.";
document.getElementById('wid').focus();
}
else if (hgt <= 0) {
document.getElementById("errors").innerHTML = "The height is less than or equal to zero.";
document.getElementById("hgt").focus();
}
else if (wid > 500) {
document.getElementById("errors").innerHTML = "The width is greater than 500.";
document.getElementById('wid').focus();
}
else if (hgt > 500) {
document.getElementById("errors").innerHTML = "The height is greater than 500.";
document.getElementById("hgt").focus();
}
else {
window.document.getElementById("area").innerHTML = area;
window.document.getElementById("perim").innerHTML = perim;
document.getElementById("errors").innerHTML = "Please see results listed above.";
}
}
function updateform (){
"use strict"
var wid = document.getElementById("wid").value;
var hgt = document.getElementById("hgt").value;
var area = wid * hgt;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
draw();
}
function mouseDown(e)
{
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
canvas.style.cursor="crosshair";
drag = true;
}
function mouseUp () {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.wid = (e.pageX - this.offsetLeft) - rect.startX;
rect.hgt = (e.pageY - this.offsetTop) - rect.startY ;
context.clearRect(0,0,canvas.width,canvas.height);
draw();
}
}
function init() {
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mouseup", mouseUp, false);
canvas.addEventListener("mousemove", mouseMove, false);
}
init();
function drawform() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2D");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0,0, rect.wid, rect.hgt);
context.fillStyle = "#FF0000"; //red color
}
function draw (){
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(rect.startX, rect.startY, rect.wid, rect.hgt);
context.fillStyle = "#378E37"; //green color
}
draw();
I have tried to do it in this way.It is working fine.The code is
$("#smt").click(function(){
var canvasel=' <canvas id="myCanvas" width="400" height="400"></canvas>'
$("#canvas").append(canvasel)
var w=$("#wid").val();
var h=$("#hgt").val();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,w,h);
ctx.stroke();
})
$("#clr").click(function(){
$("#canvas").empty();
$("#wid").val('');
$("#hgt").val('');
})
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition();
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
var width=$(".rectangle").width();
var height=$(".rectangle").height();
$("#wid").val(width);
$("#hgt").val(height)
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}
}
}
SEE DEMO HERE
NOTE:Its not working in Mozilla. I am trying to fix it.Check in Chrome

Categories

Resources