簡體   English   中英

HTML5 Canvas繪圖如何在HTML文件中編寫

[英]How we can Html5 canvas drawing write in html file

我想創建一個拖放的html UI,為此我在google上搜索了,發現html5 DnD api和canvas用於繪制元素。 但是我不知道如何將畫布圖形保存在html文件中(僅畫布元素)。

您可以使用canvas對象的toDataURL()屬性將畫布內容保存為默認為PNG格式的DataURL。

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

希望這可以幫助。

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM