Reputation: 155
This is my Javascript
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.addEventListener('click', drawLine, false);
var clicks = 0;
var lastClick = [0, 0];
$(function() {
$.each(['#f00', '#ff0', '#0f0', '#0ff', '#00f', '#f0f', '#000', '#fff'], function() {
$('#tools').append("<a href='#' onclick=\"context.strokeStyle = '" + this + "';return false;\" style='width: 10px; background: " + this + ";'></a> ");
});
});
function getCursorPosition(e) {
var x;
var y;
if (e.pageX != undefined && e.pageY != undefined) {
x = e.pageX;
y = e.pageY;
} else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return [x, y];
}
function drawLine(e) {
//context = this.getContext('2d');
x = getCursorPosition(e)[0] - this.offsetLeft;
y = getCursorPosition(e)[1] - this.offsetTop;
if (clicks != 1) {
clicks++;
} else {
context.beginPath();
context.moveTo(lastClick[0], lastClick[1]);
context.lineTo(x, y, 6);
// context.strokeStyle = '#000000';
context.stroke();
clicks = 0;
}
lastClick = [x, y];
};
This HTML
<div id='tools'>
</div>
<canvas id="canvas" width="500" height="500"></canvas>
I want to generate a new DIV when I finish drawing the line, and make it draggable, how can I do it? I not sure how can contain the line inside the DIV.
The Div should be create when I stop drawing one line.
This is the Jfiddle for a clearer picture
Upvotes: 0
Views: 171
Reputation: 5078
fyi, regarding js libs mentioned in other posts, i just checked and:
Upvotes: 0
Reputation: 1655
Canvas doesn't allow you to alter/move/scale the objects that you've just draw. Think of it as paper sheet that you color up with pencils, you can't move the pencil line around the only way is to erase the old line and draw a new one - same goes for canvas.
But! There are a bunch of libraries that make working with canvas easier, one of which is http://kineticjs.com/, another one is http://paperjs.org/. I can't claim for kineticjs, but seems it's similar to paper.js in the way that they both create an Object layer.
Briefly speaking - they provide you with API to create and change scene objects (images, lines, shapes) and deal with draw-clear-redraw Canvas concept at the backstage.
Upvotes: 1
Reputation: 990
I suggest kinetic.js for this task. Take a look at it http://kineticjs.com/
This will surely make your intended job much easier
Upvotes: 2