How to draw Rhombus/Parallelogram in canvas - javascript

I'm a beginner in using the canvas and I need to make shapes on it.
How can I draw a Rhombus/Parallelogram in a canvas?
Something like this:
I have no problem drawing in a rectangle/square with something like this:
var rectangle = new Path2D();
rectangle.rect(0, 0, width, height);
but I have no idea on how to draw a rhombus/parallelogram.
Thanks for anyone that can help.

Drag mouse from top to bottom in straight manner to draw rhombus. Works only ones then refresh browser and try again
let isDrawing = false;
let x = 0;
let y = 0;
var endPoint = [];
var startPoint = [];
const element = document.getElementById('drawFigure');
const ctx1 = element.getContext('2d');
element.addEventListener('mousedown', e => {
x = e.offsetX;
y = e.offsetY;
isDrawing = true;
startPoint.push({
x: e.offsetX,
y: e.offsetY
});
});
element.addEventListener('mousemove', e => {
if (isDrawing === false) {
x = e.offsetX;
y = e.offsetY;
console.log( "x" +x , "y" +y);
}
});
window.addEventListener('mouseup', e => {
if (isDrawing === true) {
x = e.offsetX;
y = e.offsetY;
endPoint.push({
x: e.offsetX,
y: e.offsetY,
fillcolor: 'blue'
});
drawLine();
isDrawing = false;
}
});
function drawLine() {
ctx1.beginPath();
ctx1.moveTo(startPoint[0].x,
startPoint[0].y);
var half = endPoint[0].y - startPoint[0].y
var x1 = startPoint[0].x + half
var y1 = startPoint[0].y + half / 2
ctx1.lineTo(x1, y1)
console.log(x1, y1);
ctx1.moveTo(x1, y1)
ctx1.lineTo(endPoint[0].x,
endPoint[0].y);
ctx1.lineTo(startPoint[0].x - half, y1);
ctx1.lineTo(startPoint[0].x,
startPoint[0].y);
ctx1.stroke();
}
//-------------
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(75, 75);
ctx.lineTo(135, 25);
ctx.lineTo(195, 75);
ctx.lineTo(135, 125);
ctx.closePath();
ctx.stroke();
canvas {
border: 2px dotted black;
width: 460px;
height: 330px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="drawFigure" width="560" height="260"></canvas>
<!---------------->
<h3>Hard Stoke 1/2</h3>
<canvas id="myCanvas"> </canvas>
<!-- --->
</body>
</html>

Related

How to draw on canvas and make another object not draw on the same canvas while moving

I have a blue circle which is rotating around the red circle and moves on canvas continuously in one direction as long as the button is pressed.
Now I want to draw with the red circle while it is moving when the button is pressed (trace of its path).
Problems:
when i try to draw on the canvas by not using clearRect(0,0, canvas.width, canvas.height); the blue circle also starts to draw on the canvas while moving which I don't need.
Is it possible to draw with one circle and to not draw with another circle on same canvas?
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let positionX = 100;
let positionY = 100;
let X = 50;
let Y = 50;
let angle = 0;
let mouseButtonDown = false;
document.addEventListener('mousedown', () => mouseButtonDown = true);
document.addEventListener('mouseup', () => mouseButtonDown = false);
function circle(){
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(X, Y, 20, 0, Math.PI*2);
ctx.closePath();
ctx.fill();
}
function direction(){
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(positionX + X, positionY + Y, 10, 0, Math.PI*2);
ctx.closePath();
positionX = 35 * Math.sin(angle);
positionY = 35 * Math.cos(angle);
ctx.fill();
}
function animate(){
if (mouseButtonDown) {
X += positionX / 10;
Y += positionY / 10;
} else {
angle += 0.1;
}
ctx.clearRect(0,0, canvas.width, canvas.height);
circle();
direction();
requestAnimationFrame(animate);
}
animate();
#canvas1{
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas basics</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas1"></canvas>
<script src="script.js"></script>
</body>
</html>
We could introduce a new variable:
let history = [{X,Y}]
there we can keep the positions of the red circle as it moves, and we keep everything else in your code the same, we still use clearRect to clear and then redraw all elements.
On my sample code I'm pushing items to the history on mouseup that means that history won't show until the move is done, but you can play with that see if some other event has a better experience... same with what is drawn from history, I'm drawing a dashed line but it can be anything else.
Only thing I changed was the angle angle += 0.05; it was a bit fast for me.
My sample code below will draw something like this:
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let positionX = 100
let positionY = 100
let X = canvas.width / 2;
let Y = canvas.height / 2;
let angle = 0;
let mouseButtonDown = false;
let history = [{ X, Y }]
document.addEventListener('mousedown', mousedown);
document.addEventListener('mouseup', mouseup);
function mousedown() {
mouseButtonDown = true
}
function mouseup() {
mouseButtonDown = false
history.push({ X, Y })
}
function drawHistory() {
// draw the lines for history
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.setLineDash([5, 5]);
ctx.moveTo(history[0].X, history[0].Y)
for (let i = 1; i < history.length; i++) {
ctx.lineTo(history[i].X, history[i].Y)
}
ctx.stroke();
ctx.closePath();
// draw line for current movement
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.setLineDash([10, 2]);
ctx.moveTo(history[history.length-1].X, history[history.length-1].Y)
ctx.lineTo(X, Y)
ctx.stroke();
ctx.closePath();
}
function circle() {
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(X, Y, 20, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
function direction() {
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(positionX + X, positionY + Y, 10, 0, Math.PI * 2);
ctx.closePath();
positionX = 35 * Math.sin(angle);
positionY = 35 * Math.cos(angle);
ctx.fill();
}
function animate() {
if (mouseButtonDown) {
X += positionX / 10;
Y += positionY / 10;
} else {
angle += 0.05;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle();
direction();
drawHistory();
requestAnimationFrame(animate);
}
animate();
<canvas id="canvas1"></canvas>

Drawing a circle with random color in canvas on mouse click

I am trying to develop a simple canvas application using html5 and javascript. I want to make a circle depending on the position of mouse click in the canvas. Each time user clicks in canvas a circle should be drawn. Moreover the color of circle needs to be randomly selected. I have written the random color and position function to get x and y position of mouse in canvas. But when i run nothing is happening.
Here is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="circle.js"></script>
<style type="text/css">
#testCanvas {
border: 2px solid;
}
</style>
</head>
<body>
<canvas id="testCanvas" width="400" height="400"> </canvas>
</body>
Here's my javascript code:
window.onload = init;
function init() {
// access the canvas element and its context
var canvas = document.getElementById("testCanvas");
var context = canvas.getContext("2d");
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = randomColor();
// fill a circle
context.beginPath();
context.arc(posx,posy, 30, 0, 2 * Math.PI, true);
context.fill();
context.closePath();
}
function randomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(',') + ')';
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
You need to implement a click handler for the canvas so that every time you click on it you will receive a notification in form of an event:
// access the canvas element and its context
var canvas = document.getElementById("testCanvas");
var context = canvas.getContext("2d");
// add click handler
canvas.onclick = function(e) {
var pos = getMousePos(canvas, e); // get position as before
context.fillStyle = randomColor(); // get the fill color
// fill a circle
context.beginPath(); // now we can draw the circle at click
context.arc(pos.x, pos.y, 30, 0, 2 * Math.PI); // use pos object directly like this
context.fill();
// closePath() not needed here and won't work after fill() has been called anyways
}
function randomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(',') + ')';
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas {border: 1px solid #999}
<canvas id="testCanvas" width="400" height="400"> </canvas>
Here is another example / way of adding an event handler. You can change 'click' to 'mousemove' and others to try different things.
// access the canvas element and its context
window.onload = init;
function init(){
var canvas = document.getElementById("testCanvas");
var context = canvas.getContext("2d");
function drawCircle(pos,canvas){
posx = pos.x;
posy = pos.y;
context.fillStyle = randomColor();
// fill a circle
context.beginPath();
context.arc(posx,posy, 30, 0, 2 * Math.PI, true);
context.fill();
context.closePath();
}
function randomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(',') + ')';
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
} ;
}
canvas.addEventListener('click', function(evt){
var mousePos = getMousePos(canvas,evt);
drawCircle(mousePos,canvas);
},false);
}

Draw and fill random colored circles onclick

I am using a canvas element on my web page, and need to be able to draw circles on mouse click with a different color each click. Here is the code I have, which works on some sites but not others. My question is what am I missing for this to work? I know that it only has one color currently in the code, but as it stands, I click all over the canvas and nothing happens.
var canvas = document.getElementById("cirCanvas");
var context = canvas.getContext("2d");
function createImageOnCanvas(imageId) {
canvas.style.display = "block";
document.getElementById("circles").style.overflowY = "hidden";
var img = new Image(300, 300);
img.src = document.getElementById(imageId).src;
context.drawImage(img, (0), (0)); //onload....
}
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = "#000000";
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
window.draw = draw;
<head>
<title></title>
<meta charset="utf-8">
<script src="clickCircle.js"></script>
</head>
<body>
<div id="circles"></div>
<canvas id="cirCanvas" width="250" height="250" onclick="draw (event)">
</canvas>
</body>
Below is example of a random color generator function.
Also you should try add the click event listener in an unobtrusive way.
var canvas = document.getElementById("cirCanvas");
var context = canvas.getContext("2d");
canvas.addEventListener('click', draw, false);
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = randomColor();
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
function randomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(',') + ')';
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
#cirCanvas {
border: 1px solid black;
}
<div id="circles">
<canvas id="cirCanvas" width="250" height="250"></canvas>
</div>
Here is how to change color - you can randomize the colors:
Best way to generate a random color in javascript?
or use an array of fixed colors
colors = ["001100","AA0000","00BB00"];
using
context.fillStyle = "#"+colors[Math.round(Math.random()*colors.length)];
Random version:
var canvas = document.getElementById("cirCanvas"),
context = canvas.getContext("2d");
function createImageOnCanvas(imageId) {
canvas.style.display = "block";
document.getElementById("circles").style.overflowY = "hidden";
var img = new Image(300, 300);
img.src = document.getElementById(imageId).src;
context.drawImage(img, (0), (0)); //onload....
}
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
//window.draw = draw;
<div id="circles"></div>
<canvas id="cirCanvas" width="250" height="250" onclick="draw(event)">
</canvas>
You have to implement a function which is able to generate a random color.
just use sth. like this:
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
JsFiddle example

Show rectangle on canvas when mouse move

I want to draw rectangle on canvas. Below code is working fine except when i draw rectangle it does't show path when mouse is moving. When i left the mouse then rectangle is visible on canvas.
Please help,
Thanks
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
currShape = 'rectangle',
mouseIsDown = 0,
startX, endX, startY, endY,
dot_flag = false;
var x = "white",
y = 2;
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
var imageObj = new Image(); //Canvas image Obj
imageObj.onload = function() {
ctx.drawImage(imageObj, 69, 50); //Load Image on canvas
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image
w = canvas.width; // Canvas Width
h = canvas.height; // Canvas Height
//Check Shape to be draw
eventListener();
}
function eventListener(){
if(currShape=='rectangle'){
canvas.addEventListener("mousedown",function (e) {
mouseDown(e);
}, false);
canvas.addEventListener("mousemove",function (e){
mouseXY(e);
}, false);
canvas.addEventListener("mouseup", function (e){
mouseUp(e);
}, false);
}
}
function mouseUp(eve) {
if (mouseIsDown !== 0) {
mouseIsDown = 0;
var pos = getMousePos(canvas, eve);
endX = pos.x;
endY = pos.y;
if(currShape=='rectangle')
{
drawSquare(); //update on mouse-up
}
}
}
function mouseDown(eve) {
mouseIsDown = 1;
var pos = getMousePos(canvas, eve);
startX = endX = pos.x;
startY = endY = pos.y;
if(currShape=='rectangle')
{
drawSquare(); //update on mouse-up
}
}
function mouseXY(eve) {
if (mouseIsDown !== 0) {
var pos = getMousePos(canvas, eve);
endX = pos.x;
endY = pos.y;
//drawSquare();
}
}
function drawSquare() {
// creating a square
var w = endX - startX;
var h = endY - startY;
var offsetX = (w < 0) ? w : 0;
var offsetY = (h < 0) ? h : 0;
var width = Math.abs(w);
var height = Math.abs(h);
ctx.beginPath();
ctx.globalAlpha=0.7;
ctx.rect(startX + offsetX, startY + offsetY, width, height);
ctx.fillStyle = x;
ctx.fill();
ctx.lineWidth = y;
ctx.strokeStyle = x;
ctx.stroke();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
.colortool div {
width: 15px;
height: 15px;
float: left;
margin-left: 2px;
}
.clear {
clear: both;
}
<!DOCTYPE HTML>
<html>
<body onload="init()">
<div class="canvasbody">
<canvas id="can" width="400" height="400" style="border:1px dotted #eee;"></canvas>
</div>
</body>
</html>
Here is you new JavaScript
var canvas, cnvHid, cnvRender, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
currShape = 'rectangle',
mouseIsDown = 0,
startX, endX, startY, endY,
dot_flag = false;
var x = "white",
y = 2;
function init() {
canvas = document.getElementById('can');
cnvHid = document.getElementById( "canHid" );
cnvRender = document.getElementById( "canRend" );
ctx = canvas.getContext("2d");
var imageObj = new Image(); //Canvas image Obj
imageObj.onload = function() {
ctx.drawImage(imageObj, 69, 50); //Load Image on canvas
renderAllCanvas();
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image
w = canvas.width; // Canvas Width
h = canvas.height; // Canvas Height
//Check Shape to be draw
eventListener();
}
function eventListener(){
if(currShape=='rectangle'){
cnvRender.addEventListener("mousedown",function (e) {
mouseDown(e);
renderAllCanvas();
}, false);
cnvRender.addEventListener("mousemove",function (e){
mouseXY(e);
renderAllCanvas();
}, false);
cnvRender.addEventListener("mouseup", function (e){
mouseUp(e);
renderAllCanvas();
}, false);
}
}
function mouseUp(eve) {
if (mouseIsDown !== 0) {
mouseIsDown = 0;
var pos = getMousePos(canvas, eve);
endX = pos.x;
endY = pos.y;
if(currShape=='rectangle')
{
drawSquare( canvas ); //update on mouse-up
cnvHid.getContext( "2d" ).clearRect( 0, 0, cnvHid.width, cnvHid.height );
}
}
}
function mouseDown(eve) {
mouseIsDown = 1;
var pos = getMousePos(canvas, eve);
startX = endX = pos.x;
startY = endY = pos.y;
if(currShape=='rectangle')
{
drawSquare( canvas ); //update on mouse-up
}
}
function mouseXY(eve) {
if (mouseIsDown !== 0) {
var pos = getMousePos(canvas, eve);
endX = pos.x;
endY = pos.y;
drawSquare( cnvHid, true );
}
}
function drawSquare( cnv, clear ) {
var ctx = cnv.getContext( "2d" );
if( clear && clear === true ){
ctx.clearRect( 0, 0, cnv.width, cnv.height );
}
// creating a square
var w = endX - startX;
var h = endY - startY;
var offsetX = (w < 0) ? w : 0;
var offsetY = (h < 0) ? h : 0;
var width = Math.abs(w);
var height = Math.abs(h);
ctx.beginPath();
ctx.globalAlpha=0.7;
ctx.rect(startX + offsetX, startY + offsetY, width, height);
ctx.fillStyle = x;
ctx.fill();
ctx.lineWidth = y;
ctx.strokeStyle = x;
ctx.stroke();
ctx.closePath();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function renderAllCanvas(){
var cnxRender = cnvRender.getContext( "2d" );
cnxRender.drawImage(
canvas
,0,0
,cnvRender.width,cnvRender.height
);
cnxRender.drawImage(
cnvHid
,0,0
,cnvRender.width,cnvRender.height
);
}
And here is you new HTML
<!DOCTYPE HTML>
<html>
<body onload="init()">
<div class="canvasbody">
<canvas id="can" width="400" height="400" style="display: none;"></canvas>
<canvas id="canHid" width="400" height="400" style="display: none;"></canvas>
<canvas id="canRend" width="400" height="400" style="border:1px dotted #eee;"></canvas>
</div>
</body>
</html>
In some way, you would need to keep track on the changes you make to a shape you draw on the canvas. In your case, you would start by creating a very small rectangle and then scale it according to your mouse position during your dragmove.
Currently, you only have a function which draws an entirely new rectangle but does not take any previous "state" into consideration.
I found this blogpost which could be helpful. It doesn't explain scaling in particular but it could help with the basic concepts behind so I think this would be a good way for you to find a suitable solution.
Since we are finding the canvas tag in the DOM using it’s id and then setting the drawing context of the canvas to 2D. Two things is importent here is store the information as we draw the recatangle and a bolean to check user is drawing the rectangleor not.
You can reffer these links:Drawing a rectangle using click, mouse move, and click
Draw on HTML5 Canvas using a mouse
Check the js fiddle in the given link.
Hope this will help you..
Your current code has the redraw commented out on the mouse move, which would be required to update the canvas. However your code is also destroying the image the way the rectangle is being drawn. If you retain the image as shown below and redraw it on each frame before drawing the rectangle, it might have the desired effect.
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
currShape = 'rectangle',
mouseIsDown = 0,
startX, endX, startY, endY,
dot_flag = false;
var x = "white",
y = 2,
image = null;
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
var imageObj = new Image(); //Canvas image Obj
imageObj.onload = function() {
image = imageObj;
ctx.drawImage(image, 69, 50); //Load Image on canvas
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; //Load Image
w = canvas.width; // Canvas Width
h = canvas.height; // Canvas Height
//Check Shape to be draw
eventListener();
}
function eventListener(){
if(currShape=='rectangle'){
canvas.addEventListener("mousedown",function (e) {
mouseDown(e);
}, false);
canvas.addEventListener("mousemove",function (e){
mouseXY(e);
}, false);
canvas.addEventListener("mouseup", function (e){
mouseUp(e);
}, false);
}
}
function mouseUp(eve) {
if (mouseIsDown !== 0) {
mouseIsDown = 0;
var pos = getMousePos(canvas, eve);
endX = pos.x;
endY = pos.y;
if(currShape=='rectangle')
{
drawSquare(); //update on mouse-up
}
}
}
function mouseDown(eve) {
mouseIsDown = 1;
var pos = getMousePos(canvas, eve);
startX = endX = pos.x;
startY = endY = pos.y;
if(currShape=='rectangle')
{
drawSquare(); //update on mouse-up
}
}
function mouseXY(eve) {
if (mouseIsDown !== 0) {
var pos = getMousePos(canvas, eve);
endX = pos.x;
endY = pos.y;
drawSquare();
}
}
function drawSquare() {
// draw background image
if(image) {
ctx.drawImage(image, 69, 50);
}
// creating a square
var w = endX - startX;
var h = endY - startY;
var offsetX = (w < 0) ? w : 0;
var offsetY = (h < 0) ? h : 0;
var width = Math.abs(w);
var height = Math.abs(h);
ctx.beginPath();
ctx.globalAlpha=0.7;
ctx.rect(startX + offsetX, startY + offsetY, width, height);
ctx.fillStyle = x;
ctx.fill();
ctx.lineWidth = y;
ctx.strokeStyle = x;
ctx.stroke();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
.colortool div {
width: 15px;
height: 15px;
float: left;
margin-left: 2px;
}
.clear {
clear: both;
}
<!DOCTYPE HTML>
<html>
<body onload="init()">
<div class="canvasbody">
<canvas id="can" width="400" height="400" style="border:1px dotted #eee;"></canvas>
</div>
</body>
</html>

HTML5 Canvas - Dragging Text on Canvas Problem

I want to Drag Text which is located on the Canvas , I found a tutorial How to Drag a Rectange but i could not implement it on text , This is the Following code for moving the rectangle , can some one help me to implement it on Text ?
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas Drag and Drop Test</title>
</head>
<body>
<section>
<div>
<canvas id="canvas" width="400" height="300">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
var canvas;
var ctx;
var x = 75;
var y = 50;
var dx = 5;
var dy = 3;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false;
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
ctx.fillStyle = "#FAF7F8";
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = "#444444";
rect(x - 15, y - 15, 30, 30);
}
function myMove(e){
if (dragok){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
}
}
function myDown(e){
if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
e.pageY > y -15 + canvas.offsetTop){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
dragok = true;
canvas.onmousemove = myMove;
}
}
function myUp(){
dragok = false;
canvas.onmousemove = null;
}
init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
</script>
</section>
</body>
</html>
Test
And also when i add this Code in the HEAD tag it does not work. Why is it so ?
Basic example
http://jsfiddle.net/h3BCq/1/
Prettied up one (kept rect function, added new text function, draws the bounding box for the text)
http://jsfiddle.net/h3BCq/2/
I definitely cheated. I used px for the font size to easier grab its width. You could use em's, or points though you would just need to do a conversion to pixels to get an estimated width. I Basically just removed rect, and added filltext, and modified the check to check for the text width.

Categories