canvas文字自動換行、圓角矩形畫法、產生圖片手機長按儲存

來源:互聯網
上載者:User

標籤:type   adr   長按   自動   自動換行   手動   ret   過程   縮放   

canvas的文字自動換行函數封裝

//            str:要繪製的字串//            canvas:canvas對象//            initX:繪製字串起始x座標//            initY:繪製字串起始y座標//            lineHeight:字行高,自己定義個值即可            function canvasTextAutoLine(str,canvas,initX,initY,lineHeight){                var ctx = canvas.getContext("2d");                 var lineWidth = 0;                var canvasWidth = canvas.width;                 var lastSubStrIndex= 0;                 for(let i=0;i<str.length;i++){                     lineWidth+=ctx.measureText(str[i]).width;                     //減去initX,防止邊界出現的問題                    if(lineWidth>canvasWidth-initX*2.3){                        ctx.fillText(str.substring(lastSubStrIndex,i),initX,initY);                        initY+=lineHeight;                        lineWidth=0;                        lastSubStrIndex=i;                    }                     if(i==str.length-1){                        ctx.fillText(str.substring(lastSubStrIndex,i+1),initX,initY);                    }                }          }

vanvas畫圓角矩形的函數封裝

// 封裝的一個用於繪製圓角矩形的函數.            function roundedRect(x,y,width,height,radius,color,type){              var ctx=this.ctx;              ctx.beginPath();              ctx.moveTo(x,y+radius);              ctx.lineTo(x,y+height-radius);              ctx.quadraticCurveTo(x,y+height,x+radius,y+height);              ctx.lineTo(x+width-radius,y+height);              ctx.quadraticCurveTo(x+width,y+height,x+width,y+height-radius);              ctx.lineTo(x+width,y+radius);              ctx.quadraticCurveTo(x+width,y,x+width-radius,y);              ctx.lineTo(x+radius,y);              ctx.quadraticCurveTo(x,y,x,y+radius);              ctx[type+‘Style‘] = color;              ctx.closePath();              ctx[type]();            }

直接在html中用canvas畫好的圖,在手機端是不能實現直接長按儲存到相簿的。這裡給出一種方法是:把canvas畫好的圖變成連結,引入img中,canvas隱藏,這樣實現了canvas畫圖手機長按儲存的效果。在這裡,記錄一個過程中遇到的問題,直接用設計稿的尺寸來定義畫布大小,如果尺寸太大的話,手機上開啟(只是說canvas畫好的圖未經過任何處理)會出現放不開的情況,只有手動縮放才能正常顯示。遇到這個問題,嘗試過canvas的縮放,不好使,最後也是通過上面的方法來解決的。

canvas匯出位元影像片

var canvas = document.getElementById(‘mycanvas‘);var urlimg=canvas.toDataURL(‘image/png‘, 0.92);document.getElementById("test").src = urlimg;

 

canvas文字自動換行、圓角矩形畫法、產生圖片手機長按儲存

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.