canvas toDataURL()
toDataURL() 方法可以將canvas 圖片轉換為data URI 資料。
data URI 資料就是大家常見的base64 地址,參閱Data:URL圖片一章節。
語法結構:
[JavaScript] 純文字檢視 複製程式碼canvas.toDataURL(mimeType, encoderOptions);
引數解析:
(1).mimeType:可選,規定將要轉換影象 mimeType 型別,預設 image/png,也可以是image/jpeg等。
(2).encoderOptions:可選,規定將要轉換影象的質量,值介於0-1之間,預設值為0.92。toDataURL() 方法對 PNG 圖片是無損轉換,所以規定其他 mimeType 型別,此引數才會生效。
瀏覽器相容:
(1).IE9+ 瀏覽器支援此方法。
(2).edge 瀏覽器支援此方法。
(2).谷歌瀏覽器支援此方法。
(3).火狐瀏覽器支援此方法。
(4).Opera 瀏覽器支援此方法。
(5).Safari 瀏覽器支援此方法。
程式碼例項如下:
[HTML] 純文字檢視 複製程式碼執行程式碼<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>螞蟻部落</title> <style> canvas{ border:2px dotted #d3d3d3; width:300px; height:150px; } </style> <script> window.onload= () => { let cvs=document.getElementById("canvas"); let oshow=document.getElementById("show"); let ctx=cvs.getContext("2d"); ctx.fillStyle="#0000ff"; ctx.rotate(20*Math.PI/180); ctx.fillRect(50,20,100,50); let dataURI=cvs.toDataURL("image/png",0.1); oshow.innerHTML = '<img src="'+ dataURI +'">'; } </script> </head> <body> <canvas id="canvas"></canvas> <p id="show"></p> </body> </html>
上述程式碼演示了toDataURL()方法的用法,執行效果截圖如下:
對上述程式碼分析如下:
(1).在畫布上繪製一個藍色矩形圖案。
(2).然後利用toDataURL()方法將canvas圖片轉換為base64資料。
(3).然後將轉換後的資料賦值給<img>的src屬性,最後圖片呈現在頁面之上。
(4).也可以看到,如果將要被轉換圖片是png格式,那麼將進行無損轉換,第二個引數無效。
相關文章
- canvas 2d toDataURLCanvas
- canvasCanvas
- WPF C# create canvas and draw ellipse in canvasC#Canvas
- canvas rect()Canvas
- canvas strokeStyleCanvas
- canvas lineTo()Canvas
- canvas strokeRect()Canvas
- canvas createRadialGradient()Canvas
- canvas createLinearGradient()Canvas
- canvas arc()Canvas
- canvas stroke()Canvas
- canvas fill()Canvas
- canvas fillStyleCanvas
- canvas setTransform()CanvasORM
- canvas transform()CanvasORM
- 初探canvasCanvas
- canvas closePath()Canvas
- canvas moveTo()Canvas
- canvas beginPath()Canvas
- canvas getContext()CanvasContext
- canvas getImageData()Canvas
- canvas isPointInPath()Canvas
- canvas putImageData()Canvas
- canvas drawImage()Canvas
- canvas clip()Canvas
- canvas arcTo()Canvas
- canvas createPattern()Canvas
- canvas createImageData()Canvas
- canvas restore()CanvasREST
- canvas translate()Canvas
- canvas rotate()Canvas
- canvas scale()Canvas
- canvas measureText()Canvas
- canvas fillText()Canvas
- canvas save()Canvas
- canvas clearRect()Canvas
- canvas fillRect()Canvas
- canvas(三)Canvas