简体   繁体   中英

How we can Html5 canvas drawing write in html file

I want make a drag and drop html UI, for that I search on google and I find html5 DnD api and canvas which is used for draw elements. But I don't know how I can save canvas drawing in html file (only canvas elements).

You can use toDataURL() property of canvas object to save canvas contents in an DataURL that defaults to PNG format.

var canvas=document.getElementById("YourCanvasID");
var dataURL=canvas.toDataURL();

Hope this helps.

 var canvas; var ctx; var x = 75; var y = 50; 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, 20); } function draw() { clear(); ctx.fillStyle = "#000"; rect(0,0,WIDTH,HEIGHT); ctx.fillStyle = "#fff"; 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; 
 <!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> </section> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM