關於canvas 的基礎知識就不多說了,可以進這個網址學習
http://www.w3school.com.cn/html5/html_5_canvas.asp
對於canvas 和 SVG 其實一開始個人是比較傾向於SVG多一點,不過后來工作需要,又學習了下canvas,
這兩個之間主要不同是 canvas是在JavaScript中繪制,SVG則是在 XML 繪制
其實canvas 主要的工作就是繪制圖像,圖表之類的工作,對於一些可操作的特效個人還是更喜歡用canvas + div 來實現;
如果不是特別難的需求能做到盡量做<( ̄︶ ̄)↗[GO!]
列出一個demo 這個主要功能就是canvas 內圖片拖拽
(想要拖拽什么可以直接更換JavaScript 中第3、4、5句);
說是拖拽,但也只是目測看起是 “像”是,其實在每次鼠標移動的時候都會先清掉之前畫好的,再在鼠標所在的位置重新繪制一個,全套demo如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 body,div{ 8 margin:0; 9 padding:0; 10 } 11 #d1{ 12 width:500px; 13 height: 400px; 14 border: 2px solid #00FFD1; 15 } 16 </style> 17 </head> 18 <body> 19 20 21 <div id="d1"> 22 <canvas id="myCanvas" width="500" height="400"> 23 <p>您的系統不支持此程序!</p> 24 </canvas> 25 </div> 26 27 <script> 28 const canva=document.getElementById("myCanvas"); 29 const cansText=canva.getContext("2d"); 30 31 let img = new Image(); 32 img.src="http://www.w3school.com.cn/i/ct_html5_canvas_circle.gif"; 33 cansText.drawImage(img,50,50,150,100); 34 //在事件外聲明需要用到的變量 35 let ax,ay,x,y; 36 37 canva.onmousedown=function (e) { 38 39 canva.onmousemove = function(e){ 40 x= e.clientX;y=e.clientY; 41 42 //限制移動不能超出畫布 43 (x<173)? ax=75 : ax=425; 44 (y<148)? ay=50 : ay=350; 45 46 (x < 425 && x >75)? x =e.clientX : x =ax; 47 48 (y > 50 && y <350) ? y=e.clientY : y=ay; 49 50 //先清除之前的然后重新繪制 51 cansText.clearRect(0,0,canva.width,canva.height); 52 53 cansText.drawImage(img,x-75,y-50,150,100); 54 }; 55 56 canva.onmouseup = function(){ 57 canva.onmousemove = null; 58 canva.onmouseup = null; 59 }; 60 } 61 62 </script> 63 </body> 64 </html>
補充:點擊圖片非中心移動時,會自動跳動到,圖片以當前光標為中心
原鏈:https://blog.csdn.net/freedomVenly/article/details/79042536