This question already has an answer here:
Drawing a rectangle on Canvas
(1 answer)
Closed 5 years ago.
I want to draw a square with a function like following.
How can I modify following function to create a square.
function square() {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
this.mousemove = function (ev) {
if (tool.started && checkboxSquare.checked) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started && checkboxSquare.checked) {
tool.mousemove(ev);
tool.started = false;
}
};
}
Here is a rework:
var Square;
(function(Square) {
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.style.border = "1px solid";
canvas.width = 800;
canvas.height = 800;
var context = canvas.getContext("2d");
var drawing = false;
var square = {
x: 0,
y: 0,
w: 0,
h: 0,
color: getColor()
};
var persistentSquares = [];
function getColor() {
return "rgb(" +
Math.round(Math.random() * 255) + ", " +
Math.round(Math.random() * 255) + ", " +
Math.round(Math.random() * 255) + ")";
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var pSquareIndex = 0; pSquareIndex < persistentSquares.length; pSquareIndex++) {
var pSquare = persistentSquares[pSquareIndex];
context.fillStyle = pSquare.color;
context.fillRect(pSquare.x, pSquare.y, pSquare.w - pSquare.x, pSquare.h - pSquare.y);
context.strokeRect(pSquare.x, pSquare.y, pSquare.w - pSquare.x, pSquare.h - pSquare.y);
}
context.strokeRect(square.x, square.y, square.w - square.x, square.h - square.y);
}
canvas.onmousedown = function(evt) {
square.x = evt.offsetX;
square.y = evt.offsetY;
square.w = evt.offsetX;
square.h = evt.offsetY;
drawing = true;
requestAnimationFrame(draw);
};
canvas.onmousemove = function(evt) {
if (drawing) {
square.w = evt.offsetX;
square.h = evt.offsetY;
requestAnimationFrame(draw);
}
};
function leave(evt) {
if (!drawing) {
return;
}
square.w = evt.offsetX;
square.h = evt.offsetY;
drawing = false;
persistentSquares.push(square);
square = {
x: 0,
y: 0,
w: 0,
h: 0,
color: getColor()
};
requestAnimationFrame(draw);
};
canvas.onmouseup = leave;
canvas.onmouseleave = leave;
})(Square || (Square = {}));
It's your lucky day! I was just working on something like this. If you use it for anything, be sure to credit me! ;)
Note that circle and oval are still a Work in Progress.
Link to JSFiddle that will be updated when I update the program: JSFiddle
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var mx=300;
var my=300;
var currentObject = {};
document.onmousemove = function(e){
mx=e.pageX-8;
my=e.pageY-8;
}
document.onmousedown = function(e){
var obj = document.getElementById("objSel").value;
currentObject.type=obj;
if(obj=="Rectangle"||currentObject.type=="Square"){
currentObject.x=e.pageX-8;
currentObject.y=e.pageY-8;
}
}
document.onmouseup = function(e){
mx=e.pageX-8;
my=e.pageY-8;
objects.push(complete(currentObject));
currentObject={};
}
var objects = [];
function render(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(mx-5,my);
ctx.lineTo(mx+5,my);
ctx.moveTo(mx,my-5);
ctx.lineTo(mx,my+5);
ctx.strokeStyle="black";
ctx.lineWidth=2;
ctx.stroke();
ctx.closePath();
if(currentObject.type=="Rectangle"){
ctx.beginPath();
ctx.rect(currentObject.x,currentObject.y,mx-currentObject.x,my-currentObject.y);
ctx.stroke();
}
draw(complete(currentObject));
for(var i=0;i<objects.length;i++){
draw(objects[i]);
}
}
setInterval(render,5);
render();
function complete(o){
if(o.type=="Square"){
var sidelength = Math.max(Math.abs(mx-o.x),Math.abs(my-o.y));
var fix = function(input){
if(input==0){
return 1;
} else {
return input;
}
};
o.length=fix(Math.sign(mx-o.x))*sidelength;
o.height=fix(Math.sign(my-o.y))*sidelength;
} else if(o.type=="Rectangle"){
o.length=mx-o.x;
o.height=my-o.y;
}
return o;
}
function draw(o){
if(o.type=="Square"||o.type=="Rectangle"){
ctx.beginPath();
ctx.rect(o.x,o.y,o.length,o.height);
ctx.stroke();
}
}
<canvas id="canvas" style="border:1px solid black;" width="500" height="500">Please use a browser that supports the canvas element and make sure your Javascript is working properly.</canvas>
<br>
<span id="testing"></span>
<select id="objSel">
<option>Square</option>
<option>Rectangle</option>
<option>Circle</option>
<option>Oval</option>
</select>
Related
I have this triangle code, but it seems to be not working. The code should act something like in this image, but instead, it only works in coding with Chrome platform.
What might be the reason behind that? Here is a fiddle.
function createTriangle(x1,y1,x2,y2,x3,y3,fillcolor,strokecolor,stroke) {
var triangle = new Object();
triangle.x1 =x1;
triangle.y1 = y1;
triangle.x2 = x2;
triangle.y2 = y2;
triangle.x3 = x3;
triangle.y3 = y3;
triangle.fillcolor = fillcolor;
triangle.draw = function() {
draw.triangle(this.x1, this.y1, this.x2, this.y2, this.x3, this.y3, this.fillcolor, this.strokecolor, this.stroke);
}
return triangle;
}
var triangle = createTriangle(350,100,360,100,360,360,'blue','black',6);
triangle.draw();
triangle.pointRight = true;
function moveTriangle() {
if (triangle.pointRight){
triangle.x1 += 2;
} else {
triangle.x1 -= 2;
}
if(triangle.x1 >= 300) {
triangle.pointRight = false;
} else if (triangle.x1 <= 250) {
triangle.pointRight = true;
}
triangle.draw();
setTimeout('moveTriangle();', 20)
}
moveTriangle();
I've created a simple animation trangle to the rectangle, it's not perfect, because I've no much time but maybe it'll helpful to you:
let initCoor = {
x1: ctx.canvas.width,
y1: 0,
x2:ctx.canvas.width,
y2:ctx.canvas.height/2,
x3:ctx.canvas.width,
y3:ctx.canvas.height/2,
x4:(ctx.canvas.width-ctx.canvas.width/5),
y4:0,
};
function initCanvas(){
ctx.clearRect(0, 0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle = 'rgba(0,0,0,1)';
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
}
function draw_triangle(x1,y1,x2,y2,x3,y3,x4,y4, color) {
ctx.save();
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.lineTo(x3,y3);
ctx.lineTo(x4,y4)
ctx.fillStyle = color;
ctx.fill();
}
function setAnimate(){
initCoor.x4<=0?initCoor.x4=0:initCoor.x4-=10;
if(initCoor.y2>=ctx.canvas.height && initCoor.y3>=ctx.canvas.height){
initCoor.y2 = ctx.canvas.height;
initCoor.y3 = ctx.canvas.height;
if(initCoor.x3 <=0){
initCoor.x3=0
window.clearInterval(int);
}else{
initCoor.x3-=10
};
} else {
initCoor.y2+=10;
initCoor.y3+=10;
}
draw_triangle(initCoor.x1,initCoor.y1,initCoor.x2,initCoor.y2,initCoor.x3,initCoor.y3,initCoor.x4,initCoor.y4, '#CCC');
}
And working fiddle: https://jsfiddle.net/c7h5n34z/1/
My game components won't draw onto the canvas after adding if/else statement.
The statement only checks if the game piece hit the game obstacle.
I tried changing attributes and rewrite some functions but it seems the problem hasn't been fixed.
Whenever I remove the if/else function, the components draw.
Here is part of the code that holds that if/else function:
if(gamePieceBorder.crashGame(gameObstacle) || gamePieceRed.crashGame(gameObstacle))
{
gameArea.stop();
}
else
{
obstacle.update();
gamePieceBorder.pos();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.pos();
gamePieceRed.move();
gamePieceRed.update();
gameArea.clear();
}
For me not pasting an entire code, here is the pastebin link to the code: https://pastebin.com/HuiR7r7D
How can I get the components to draw? If someone fixes the code, what was the issue? I am not an expert at javascript but only a beginner.
There are several problems:
window.EventListener should be window.addEventListener
keyup and keydown should have no upper case letters
gameObstacle in that if is undefined (should be obstacle probably)
clear method should be called before drawing, not after it
Here is the corrected script: https://pastebin.com/bXpQ2qvB
//-----------------------------------------Variables
var gamePieceRed;
var gamePieceBorder;
var gameObstacle;
//-----------------------------------------
//-----------------------------------------Main game function
function startGame()
{
gamePieceRed = new component(22, 22, "rgb(255, 132, 156)", 10, 120);
gamePieceBorder = new component(24, 24, "black", 9, 119);
obstacle = new component(10, 200, "rgb(64, 0 ,12)", 300, 120)
gameArea.start();
}
//-----------------------------------------
//-----------------------------------------Creating game area and applying controls
var gameArea =
{
canvas : document.createElement("canvas"), start : function()
{
this.canvas.width = 510;
this.canvas.height = 280;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(gameUpdate, 20);
window.addEventListener("keydown", function (e)
{
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = true;
}, true)
window.addEventListener("keyup", function (e)
{
gameArea.keys[e.keyCode] = false;
}, true)
},
clear : function()
{
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function()
{
clearInterval(this.interval);
},
keyboard: function() {
if (this.keys) {
if (this.keys[37]) {gamePieceBorder.speedX = gamePieceRed.speedX = -2;}
else if (this.keys[39]) {gamePieceBorder.speedX = gamePieceRed.speedX = 2;}
else {gamePieceBorder.speedX = gamePieceRed.speedX = 0;}
if (this.keys[38]) {gamePieceBorder.speedY = gamePieceRed.speedY = -2;}
else if (this.keys[40]) {gamePieceBorder.speedY = gamePieceRed.speedY = 2;}
else {gamePieceBorder.speedY = gamePieceRed.speedY = 0;}
}
}
}
//-----------------------------------------
//-----------------------------------------Game component
function component(width, height, color, x, y)
{
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.update = function()
{
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height)
}
this.move = function()
{
this.x += this.speedX;
this.y += this.speedY;
}
this.crashGame = function(obj)
{
var left = this.x;
var right = this.x + (this.width);
var top = this.y;
var bottom = this.y + (this.height);
var otherLeft = obj.x;
var otherRight = obj.x + (obj.width);
var otherTop = obj.y;
var otherBottom = obj.y + (obj.height);
var crash = true;
if (bottom < otherTop || top > otherBottom || right < otherLeft || left > otherRight)
{
crash = false;
}
return crash;
}
}
//-----------------------------------------
//-----------------------------------------Game area updater
function gameUpdate()
{
if(gamePieceBorder.crashGame(obstacle) || gamePieceRed.crashGame(obstacle))
{
gameArea.stop();
}
else
{
gameArea.clear();
obstacle.update();
gameArea.keyboard();
gamePieceBorder.move();
gamePieceBorder.update();
gamePieceRed.move();
gamePieceRed.update();
}
}
//-----------------------------------------
<html>
<style>
canvas
{
border: 1px solid #d3d3d3;
background-image: url("https://ak0.picdn.net/shutterstock/videos/22492090/thumb/1.jpg");
}
</style>
<body onload = "startGame()">
</body>
</html>
Here I'm trying to draw on a html5 canvas as well as upload some images and drag them within the canvas. The problem is I can do one or the other but not both.
What I've realised is that the canvas must be Cleared before dragging takes place but by doing that I'm clearing the drawing and if I don't clear the canvas it draws but dragging an image leaves trail behind. Can anyone point me to right direction please.
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
img = document.getElementById("drag");
canvas.addEventListener("mousemove", function (e) { findxy('move', e) }, false);
canvas.addEventListener("mousedown", function (e) { findxy('down', e) }, false);
canvas.addEventListener("mouseup", function (e) { findxy('up', e) }, false);
canvas.addEventListener("mouseout", function (e) { findxy('out', e) }, false);
imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var contexts = [];
contexts.push(canvas.getContext('2d'));
function clearAll() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
canvas.onclick = function (e) { handleClick(e, 1); };
function handleClick(e, contextIndex) {
e.stopPropagation();
var mouseX = parseInt(e.clientX - e.target.offsetLeft);
var mouseY = parseInt(e.clientY - e.target.offsetTop);
// clearAll();
for (var i = 0; i < states.length; i++) {
var state = states[i];
if (state.dragging) {
state.dragging = false;
state.draw();
continue;
}
if (state.contextIndex === contextIndex
&& mouseX > state.x && mouseX < state.x + state.width
&& mouseY > state.y && mouseY < state.y + state.height)
{
state.dragging = true;
state.offsetX = mouseX - state.x;
state.offsetY = mouseY - state.y;
state.contextIndex = contextIndex;
}
state.draw();
}
}
canvas.onmousemove = function (e) { handleMousemove(e, 1); }
function handleMousemove(e, contextIndex) {
e.stopPropagation();
var mouseX = parseInt(e.clientX - e.target.offsetLeft);
var mouseY = parseInt(e.clientY - e.target.offsetTop);
// clearAll();
for (var i = 0; i < states.length; i++) {
var state = states[i];
if (state.dragging) {
state.x = mouseX - state.offsetX;
state.y = mouseY - state.offsetY;
state.contextIndex = contextIndex;
}
state.draw();
}
}
var states = [];
states.push(addState(0, 0, img));
function addState(x, y, image) {
state = {}
state.dragging = false;
state.contextIndex = 1;
state.image = image;
state.x = x;
state.y = y;
state.width = image.width;
state.height = image.height;
state.offsetX = 0;
state.offsetY = 0;
state.draw = function () {
var context = contexts[this.contextIndex - 1];
if (this.dragging) {
context.strokeStyle = 'red';
context.strokeRect(this.x, this.y, this.width + 5, this.height + 5);
}
context.drawImage(this.image, this.x, this.y);
};
state.draw();
return(state);
}
}//end of init()
var imgArray = [];
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
imgArray.push(img);
for(i = 0; i < imgArray.length; i++){
img.src = imgArray[i];
img.setAtX = i * 50;
img.setAtY = i * 0;
img.onload = function() {
ctx.drawImage(this, this.setAtX, this.setAtY);
};
img.src = event.target.result;
}
};
reader.readAsDataURL(e.target.files[0]);
}
function findxy(res, e) {
if (res === 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res === 'up' || res === "out") {
flag = false;
}
if (res === 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
//Draw lines or text
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
ctx.fillStyle = x;
ctx.font = "Italic Bold 14pt Times, serif";
ctx.fillText(message, prevX, prevY);
}
Here is a mashup of the code i linked to and your own.
All parameters related to drawing the image and translating it around the canvas is covered.
var canvas = document.getElementById("canvas");
var ctx;
var x = 75;
var y = 50;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false;
var img = document.getElementById("img");
var lines = [{
x: x,
y: y
}];
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, 1000/24);
}
function draw() {
clear();
ctx.drawImage(img, x - img.width / 2, y - img.height / 2);
ctx.beginPath();
ctx.moveTo(lines[0].x,lines[0].y);
for(var i = 1; i < lines.length; i++) {
var line = lines[i];
ctx.lineTo(lines[i].x,lines[i].y);
}
ctx.stroke();
ctx.closePath();
//rect(x - 15, y - 15, 30, 30);
}
function myMove(e) {
if (dragok) {
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
lines = lines.slice(lines.length - 100)
lines.push({
x: x,
y: y
});
}
}
function myDown(e) {
if (e.pageX < x + img.width / 2 + canvas.offsetLeft && e.pageX > x - img.width / 2 +
canvas.offsetLeft && e.pageY < y + img.height / 2 + canvas.offsetTop &&
e.pageY > y - img.height / 2 + 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;
//Change image for the heck of it ^^
setInterval(function() {
img.src = 'https://placeholdit.imgix.net/~text?txtsize=60&txt=' +
Math.floor(Math.random() * 10) +
'&w=100&h=100';
}, 3000)
<canvas id="canvas" width="400" height="300">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<img id="img" src="https://placeholdit.imgix.net/~text?txtsize=60&txt=1&w=100&h=100">
Updated my answer to draw lines
My final code that's working , I had to add two canvases one for the drawing and one for the dragging images. Fabric frame work helped a lot. https://jsfiddle.net/tn07Bond/982s4bgv/2/
<div id="canvasesdiv">
<canvas id="images" width=600 height=400 style="position: absolute;
left: 0;
top: 0;
border: 1px solid blue;
z-index: 1;">
This text is displayed if your browser does not support HTML5 Canvas</canvas>
<canvas id="drawing" width=600 height=400 style="position: absolute;
left: 0;
top: 0;
border: 1px solid red;
z-index: 2;">
This text is displayed if your browser does not support HTML5 Canvas</canvas>
<input type="file" id="imageLoader" class="imageLoader" name="imageLoader"/>
<input type="image" src="images/PenForCanvas.png" alt="pen" title="Draw on canvas"
id="Drawing" style="cursor: pointer; margin: 5px 0 0 200px;">
<input type="image" src="images/drag.png" alt="drag" title="Drag this image" id="Images" style="cursor: pointer;">
</div>
<script>
var drawing, drawingCtx,images,imagesCtx, message = "", img, imageLoader, prevX = 10, currX = 10, prevY = 10, currY = 10,
dot_flag = false, flag = false, x = "black", y = 2, formElement, canvasLeft, canvasTop, imgData, data,
startOffsetX = 0, startOffsetY = 0;
(function () {
// Drawing canvas
drawing = document.getElementById("drawing");
drawingCtx = drawing.getContext("2d");
//Uploading and dragging images
images = new fabric.Canvas('images');
document.getElementById('imageLoader').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:40, height:40}).scale(0.9);
images.add(oImg).renderAll();
var a = images.setActiveObject(oImg);
var dataURL = images.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
w = drawing.width;
h = drawing.height;
//Mouse events
drawing.addEventListener("mousemove", function (e) { findxy('move', e) }, false);
drawing.addEventListener("mousedown", function (e) { findxy('down', e) }, false);
drawing.addEventListener("mouseup", function (e) { findxy('up', e) }, false);
drawing.addEventListener("mouseout", function (e) { findxy('out', e) }, false);
Drawing = document.getElementById("Drawing");
Drawing.addEventListener("click", bringDrawingToFront);
Images = document.getElementById("Images");
Images.addEventListener("click", bringImagesToFront);
imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', bringImagesToFront);
//Drawing
function findxy(res, e) {
if (res === 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - drawing.offsetLeft;
currY = e.clientY - drawing.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
drawingCtx.beginPath();
drawingCtx.fillStyle = x;
drawingCtx.fillRect(currX, currY, 2, 2);
drawingCtx.closePath();
dot_flag = false;
}
}
if (res === 'up' || res === "out") {
flag = false;
}
if (res === 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - drawing.offsetLeft;
currY = e.clientY - drawing.offsetTop;
draw();
}
}
}
function save() {
imgData = drawingCtx.getImageData(0, 0, drawing.width, drawing.height);
}
function restore() {
drawingCtx.putImageData(imgData, 0, 0);
}
function bringDrawingToFront() {
drawing.style.zIndex = 1;
document.getElementById("images").style.zIndex = 0;
}
function bringImagesToFront() {
drawing.style.zIndex = 0;
document.getElementById("images").style.zIndex = 1;
}
//Draw lines or text
function draw() {
drawingCtx.beginPath();
drawingCtx.moveTo(prevX, prevY);
drawingCtx.lineTo(currX, currY);
drawingCtx.strokeStyle = x;
drawingCtx.lineWidth = y;
drawingCtx.stroke();
drawingCtx.closePath();
drawingCtx.fillStyle = x;
drawingCtx.font = "Italic Bold 14pt Times, serif";
drawingCtx.fillText(message, prevX, prevY);
save();
}
})();
</script>
I want change the middle point of canvas quadratic curve which is far away from the line while dragging middle point. On dragging i want to stick with the link as now its increasing the distance of the middle point.http://jsfiddle.net/ashishbhatt/yqgak7eq/1/
http://s25.postimg.org/hegxhlgrj/123123.jpg
Please check the above reference image for the same.
Code :
(function() {
var canvas, ctx, code, point, style, drag = null, dPoint;
// define initial points
function Init(quadratic) {
point = {
p1: { x:0, y:100 },
p2: { x:200, y:100 }
};
if (quadratic) {
point.cp1 = { x: 100, y: 50 };
}
else {
point.cp1 = { x: 100, y: 100 };
point.cp2 = { x: 100, y: 100 };
}
// default styles
style = {
curve: { width: 2, color: "#333" },
cpline: { width: 1, color: "#C00" },
point: { radius: 6, width: 1, color: "#900", fill: "rgba(200,200,200,0.5)", arc1: 0, arc2: 2 * Math.PI }
}
// line style defaults
ctx.lineCap = "round";
ctx.lineJoin = "round";
// event handlers
canvas.onmousedown = DragStart;
canvas.onmousemove = Dragging;
canvas.onmouseup = canvas.onmouseout = DragEnd;
DrawCanvas();
}
// draw canvas
function DrawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// control lines
ctx.lineWidth = style.cpline.width;
ctx.strokeStyle = style.cpline.color;
ctx.beginPath();
//ctx.moveTo(point.p1.x, point.p1.y);
//ctx.lineTo(point.cp1.x, point.cp1.y);
if (point.cp2) {
//ctx.moveTo(point.p2.x, point.p2.y);
//ctx.lineTo(point.cp2.x, point.cp2.y);
}
else {
//ctx.lineTo(point.p2.x, point.p2.y);
}
ctx.stroke();
// curve
ctx.lineWidth = style.curve.width;
ctx.strokeStyle = style.curve.color;
ctx.beginPath();
ctx.moveTo(point.p1.x, point.p1.y);
if (point.cp2) {
//ctx.bezierCurveTo(point.cp1.x, point.cp1.y, point.cp2.x, point.cp2.y, point.p2.x, point.p2.y);
}
else {
ctx.quadraticCurveTo(point.cp1.x, point.cp1.y, point.p2.x, point.p2.y);
}
ctx.stroke();
// control points
for (var p in point) {
ctx.lineWidth = style.point.width;
ctx.strokeStyle = style.point.color;
ctx.fillStyle = style.point.fill;
ctx.beginPath();
ctx.arc(point[p].x, point[p].y, style.point.radius, style.point.arc1, style.point.arc2, true);
ctx.fill();
ctx.stroke();
}
ShowCode();
}
// show canvas code
function ShowCode() {
var myCounter = 0;
if(point.cp1.y < 100){
myCounter = point.cp1.y-100;
}else if(point.cp1.y > 100){
myCounter = point.cp1.y-100;
}
if (code) {
code.firstChild.nodeValue = myCounter
}
}
// start dragging
function DragStart(e) {
e = MousePos(e);
var dx, dy;
for (var p in point) {
//console.log(p)
//dx = point[p].x - e.x;
if(p == 'cp1'){
dy = point[p].y - e.y;
if ((dy * dy) < style.point.radius * style.point.radius) {
drag = p;
dPoint = e;
canvas.style.cursor = "move";
return;
}
}
}
}
// dragging
function Dragging(e) {
if (drag) {
e = MousePos(e);
//point[drag].x += e.x - dPoint.x;
point[drag].y += e.y - dPoint.y;
dPoint = e;
DrawCanvas();
}
}
// end dragging
function DragEnd(e) {
drag = null;
canvas.style.cursor = "default";
DrawCanvas();
}
// event parser
function MousePos(event) {
event = (event ? event : window.event);
return {
//x: event.pageX - canvas.offsetLeft,
y: event.pageY - canvas.offsetTop
}
}
// start
canvas = document.getElementById("canvasSettings");
code = document.getElementById("code");
if (canvas.getContext) {
ctx = canvas.getContext("2d");
Init(canvas.className == "quadratic");
}
})();
Here is my fiddle
HTML for Canvas:
<div id="canvasDiv"><canvas id="myNewCanvasColumn" width="490" height="220"></canvas></div>
I am working on a canvas drawing tool. Problem is that, i am unable to select the appropriate sizes for drawing. I have defined sizes like "small, normal, large and huge". Default selection is normal. I have wrote some function to determine the radius, but it is not working. Can some one help me?
Thanks a ton..!
You can set different context.lineWidth to set the cursor size. I've updated the code with that.
function redraw() {
clickSize.length = 0;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
//context.strokeStyle = "#df4b26";
context.lineJoin = "round";
//context.lineWidth = 5;
for (var i = 0; i < clickX.length; i++) {
context.beginPath();
if (clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
context.moveTo(clickX[i] - 1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.strokeStyle = clickColor[i];
context.lineWidth = cursorSize;
//alert('radius is'+context.lineWidth)
context.stroke();
}
}
$('#choosesmall').click(function () {
curSize = "small";
cursorSize = 1;
});
$('#choosenormal').click(function () {
curSize = "normal";
cursorSize = 3;
});
$('#chooselarge').click(function () {
curSize = "large";
cursorSize = 5;
});
$('#choosehuge').click(function () {
curSize = "huge";
cursorSize = 7;
});
See the Fiddle
Edit
$(document).ready(function () {
/* Declaration global Variables */
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
var context;
var canvas;
var colorPurple = "#cb3594";
var colorGreen = "#659b41";
var colorYellow = "#ffcf33";
var colorBrown = "#986928";
var colorRed = "#ff0000";
var curColor = colorPurple;
var clickColor = new Array();
var clickSize = new Array();
var curSize = 1;
/* End of Declaring Global Variables */
context = document.getElementById('myNewCanvasColumn').getContext("2d");
var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', 700);
canvas.setAttribute('height', 300);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if (typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
var radius;
var i = 0;
context = canvas.getContext("2d");
/* Event Handlers for drawing */
$('#canvas').mousedown(function (e) {
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mousemove(function (e) {
if (paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').mouseup(function (e) {
paint = false;
});
$('#canvas').mouseleave(function (e) {
paint = false;
});
$("#clear").click(function () {
clearDrawing();
});
/* End of Event Handlers */
/* Custom Color Pickers */
$('#choosegreen').click(function () {
curColor = "#659b41";
});
$('#choosepurple').click(function () {
curColor = "#cb3594";
});
$('#chooseyellow').click(function () {
curColor = "#ffcf33";
});
$('#choosebrown').click(function () {
curColor = "#986928";
});
$('#choosered').click(function () {
curColor = "#ff0000";
});
/* End of Custom Color Pickers */
/* Custom Size Picker */
$('#choosesmall').click(function () {
curSize = 1;
});
$('#choosenormal').click(function () {
curSize = 3;
});
$('#chooselarge').click(function () {
curSize = 5;
});
$('#choosehuge').click(function () {
curSize = 7;
});
/* End of Custom Size Picker */
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
clickColor.push(curColor);
clickSize.push(curSize);
// alert(clickSize);
}
function clearDrawing() {
clickX.length = 0;
clickY.length = 0;
clickDrag.length = 0;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
}
function redraw() {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
//context.strokeStyle = "#df4b26";
context.lineJoin = "round";
//context.lineWidth = 5;
for (var i = 0; i < clickX.length; i++) {
context.beginPath();
if (clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
context.moveTo(clickX[i] - 1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.strokeStyle = clickColor[i];
context.lineWidth = clickSize[i];
// alert(clickColor[i]);
//alert('radius is'+context.lineWidth)
context.stroke();
}
}
});
Updated Fiddle