lineas figuras examples etiquetas ejemplos dibujar html5 canvas gesture-recognition gestures

figuras - html5 canvas drawing



Dibuja en HTML5 Canvas usando un mouse (9)

Quiero dibujar en un Lienzo HTML usando un mouse (ej: dibujar una firma, dibujar un nombre, ...)

Por favor, ayúdame, ¿cómo puedo hacer? Por favor, dame un código fuente. Gracias


Alco mira esto:
Ejemplo:
https://github.com/williammalone/Simple-HTML5-Drawing-App

Documentación:
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/

Este documento incluye los siguientes códigos:

HTML:

<canvas id="canvas" width="490" height="220"></canvas>

JS:

context = document.getElementById(''canvas'').getContext("2d"); $(''#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'').mouseup(function(e){ paint = false; }); $(''#canvas'').mouseleave(function(e){ paint = false; }); var clickX = new Array(); var clickY = new Array(); var clickDrag = new Array(); var paint; function addClick(x, y, dragging) { clickX.push(x); clickY.push(y); clickDrag.push(dragging); } //Also redraw function redraw(){ context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas 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.stroke(); } }

Y otro ejemplo impresionante
http://perfectionkills.com/exploring-canvas-drawing-techniques/


Aquí está mi lienzo de trabajo muy simple dibujar y borrar.

https://jsfiddle.net/richardcwc/d2gxjdva/

//Canvas var canvas = document.getElementById(''canvas''); var ctx = canvas.getContext(''2d''); //Variables var canvasx = $(canvas).offset().left; var canvasy = $(canvas).offset().top; var last_mousex = last_mousey = 0; var mousex = mousey = 0; var mousedown = false; var tooltype = ''draw''; //Mousedown $(canvas).on(''mousedown'', function(e) { last_mousex = mousex = parseInt(e.clientX-canvasx); last_mousey = mousey = parseInt(e.clientY-canvasy); mousedown = true; }); //Mouseup $(canvas).on(''mouseup'', function(e) { mousedown = false; }); //Mousemove $(canvas).on(''mousemove'', function(e) { mousex = parseInt(e.clientX-canvasx); mousey = parseInt(e.clientY-canvasy); if(mousedown) { ctx.beginPath(); if(tooltype==''draw'') { ctx.globalCompositeOperation = ''source-over''; ctx.strokeStyle = ''black''; ctx.lineWidth = 3; } else { ctx.globalCompositeOperation = ''destination-out''; ctx.lineWidth = 10; } ctx.moveTo(last_mousex,last_mousey); ctx.lineTo(mousex,mousey); ctx.lineJoin = ctx.lineCap = ''round''; ctx.stroke(); } last_mousex = mousex; last_mousey = mousey; //Output $(''#output'').html(''current: ''+mousex+'', ''+mousey+''<br/>last: ''+last_mousex+'', ''+last_mousey+''<br/>mousedown: ''+mousedown); }); //Use draw|erase use_tool = function(tool) { tooltype = tool; //update }

canvas { cursor: crosshair; border: 1px solid #000000; }

<canvas id="canvas" width="800" height="500"></canvas> <input type="button" value="draw" onclick="use_tool(''draw'');" /> <input type="button" value="erase" onclick="use_tool(''erase'');" /> <div id="output"></div>


Aquí hay una muestra de trabajo.

<html> <script type="text/javascript"> var canvas, ctx, flag = false, prevX = 0, currX = 0, prevY = 0, currY = 0, dot_flag = false; var x = "black", y = 2; function init() { canvas = document.getElementById(''can''); ctx = canvas.getContext("2d"); w = canvas.width; h = canvas.height; 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); } function color(obj) { switch (obj.id) { case "green": x = "green"; break; case "blue": x = "blue"; break; case "red": x = "red"; break; case "yellow": x = "yellow"; break; case "orange": x = "orange"; break; case "black": x = "black"; break; case "white": x = "white"; break; } if (x == "white") y = 14; else y = 2; } function draw() { ctx.beginPath(); ctx.moveTo(prevX, prevY); ctx.lineTo(currX, currY); ctx.strokeStyle = x; ctx.lineWidth = y; ctx.stroke(); ctx.closePath(); } function erase() { var m = confirm("Want to clear"); if (m) { ctx.clearRect(0, 0, w, h); document.getElementById("canvasimg").style.display = "none"; } } function save() { document.getElementById("canvasimg").style.border = "2px solid"; var dataURL = canvas.toDataURL(); document.getElementById("canvasimg").src = dataURL; document.getElementById("canvasimg").style.display = "inline"; } 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(); } } } </script> <body onload="init()"> <canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas> <div style="position:absolute;top:12%;left:43%;">Choose Color</div> <div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div> <div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div> <div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div> <div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div> <div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div> <div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div> <div style="position:absolute;top:20%;left:43%;">Eraser</div> <div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div> <img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;"> <input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;"> <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;"> </body> </html>


Avíseme si tiene problemas para implementar esto. Utiliza processing.js y tiene características para cambiar colores y hacer que el punto de dibujo sea más grande y más pequeño.

<html> <head> <!--script librarires--> <script type="text/javascript" src="processing.js"></script> <script type="text/javascript" src="init.js"></script> <!--styles --> <style type="text/css" src="stylesheet.css"> </style> </head> <body> <!--toolbox --> <div id="draggable toolbox"></div> <script type="application/processing"> // new script int prevx, prevy; int newx, newy; boolean cliked; color c1 = #000000; int largeur=2; int ps = 20; int px = 50; int py = 50; void setup() { size(500,500); frameRate(25); background(50); prevx = mouseX; prevy = mouseY; cliked = false; } void draw() { //couleur noStroke(0); fill(#FFFFFF);//blanc rect(px, py, ps, ps); fill(#000000); rect(px, py+(ps), ps, ps); fill(#FF0000); rect(px, py+(ps*2), ps, ps); fill(#00FF00); rect(px, py+(ps*3), ps, ps); fill(#FFFF00); rect(px, py+(ps*4), ps, ps); fill(#0000FF); rect(px, py+(ps*5), ps, ps); //largeur fill(#FFFFFF); rect(px, py+(ps*7), ps, ps); fill(#FFFFFF); rect(px, py+(ps*8), ps, ps); stroke(#000000); line(px+2, py+(ps*7)+(ps/2), px+(ps-2), py+(ps*7)+(ps/2)); line(px+(ps/2), py+(ps*7)+1, px+(ps/2), py+(ps*8)-1); line(px+2, py+(ps*8)+(ps/2), px+(ps-2), py+(ps*8)+(ps/2)); if(cliked==false){ prevx = mouseX; prevy = mouseY; } if(mousePressed) { cliked = true; newx = mouseX; newy = mouseY; strokeWeight(largeur); stroke(c1); line(prevx, prevy, newx, newy); prevx = newx; prevy = newy; }else{ cliked= false; } } void mouseClicked() { if (mouseX>=px && mouseX<=(px+ps)){ //couleur if (mouseY>=py && mouseY<=py+(ps*6)){ c1 = get(mouseX, mouseY); } //largeur if (mouseY>=py+(ps*7) && mouseY<=py+(ps*8)){ largeur += 2; } if (mouseY>=py+(ps*8) && mouseY<=py+(ps*9)){ if (largeur>2){ largeur -= 2; } } } } </script><canvas></canvas> </body> </html>



Creo que otros ejemplos son demasiado complicados. Este es más simple y solo JS ...

// create canvas element and append it to document body var canvas = document.createElement(''canvas''); document.body.appendChild(canvas); // some hotfixes... ( ≖_≖) document.body.style.margin = 0; canvas.style.position = ''fixed''; // get canvas 2D context and set him correct size var ctx = canvas.getContext(''2d''); resize(); // last known position var pos = { x: 0, y: 0 }; window.addEventListener(''resize'', resize); document.addEventListener(''mousemove'', draw); document.addEventListener(''mousedown'', setPosition); document.addEventListener(''mouseenter'', setPosition); // new position from mouse event function setPosition(e) { pos.x = e.clientX; pos.y = e.clientY; } // resize canvas function resize() { ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight; } function draw(e) { // mouse left button must be pressed if (e.buttons !== 1) return; ctx.beginPath(); // begin ctx.lineWidth = 5; ctx.lineCap = ''round''; ctx.strokeStyle = ''#c0392b''; ctx.moveTo(pos.x, pos.y); // from setPosition(e); ctx.lineTo(pos.x, pos.y); // to ctx.stroke(); // draw it! }


Esta es la manera más directa de crear una aplicación de dibujo con lienzo:

  1. Adjunte un mousedown mousemove mousedown , mousemove y mouseup al DOM de mouseup
  2. en mousedown , obtenga las coordenadas del mouse y use el método moveTo() para beginPath() el cursor de dibujo y el método beginPath() para comenzar una nueva ruta de dibujo.
  3. en mousemove , agrega continuamente un nuevo punto a la ruta con lineTo() y colorea el último segmento con stroke() .
  4. en mouseup , establece una bandera para deshabilitar el dibujo.

A partir de ahí, puede agregar todo tipo de otras funciones, como darle al usuario la capacidad de elegir un grosor de línea, color, trazos de pincel e incluso capas.


Estaba buscando utilizar este método para las firmas, encontré una muestra en http://codetheory.in/ .

He agregado el siguiente código a jsfiddle

Html:

<div id="sketch"> <canvas id="paint"></canvas> </div>

Javascript:

(function() { var canvas = document.querySelector(''#paint''); var ctx = canvas.getContext(''2d''); var sketch = document.querySelector(''#sketch''); var sketch_style = getComputedStyle(sketch); canvas.width = parseInt(sketch_style.getPropertyValue(''width'')); canvas.height = parseInt(sketch_style.getPropertyValue(''height'')); var mouse = {x: 0, y: 0}; var last_mouse = {x: 0, y: 0}; /* Mouse Capturing Work */ canvas.addEventListener(''mousemove'', function(e) { last_mouse.x = mouse.x; last_mouse.y = mouse.y; mouse.x = e.pageX - this.offsetLeft; mouse.y = e.pageY - this.offsetTop; }, false); /* Drawing on Paint App */ ctx.lineWidth = 5; ctx.lineJoin = ''round''; ctx.lineCap = ''round''; ctx.strokeStyle = ''blue''; canvas.addEventListener(''mousedown'', function(e) { canvas.addEventListener(''mousemove'', onPaint, false); }, false); canvas.addEventListener(''mouseup'', function() { canvas.removeEventListener(''mousemove'', onPaint, false); }, false); var onPaint = function() { ctx.beginPath(); ctx.moveTo(last_mouse.x, last_mouse.y); ctx.lineTo(mouse.x, mouse.y); ctx.closePath(); ctx.stroke(); }; }());