1. 程式人生 > 實用技巧 >canvas在小程式中新增圖片(本地圖片/網路圖片),在html中新增圖片

canvas在小程式中新增圖片(本地圖片/網路圖片),在html中新增圖片

新增圖片網路圖片:

wxml檔案中:

<canvas canvas-id="canvas" style="border:1px solid #f00;height: 400rpx; width: 400rpx;"></canvas>

js檔案中:

onShow:function(){
wx.getImageInfo({//getImageInfo獲取圖片資訊。網路圖片需先配置download域名才能生效。 src:'http://chuantu.xyz/t6/741/1605489019x2073447983.png', success:function(res){ constctx=wx.createCanvasContext('canvas'); letwidth=400; letheight=400; ctx.drawImage(res.path,0,0,width,height);//res.path網路圖片請求回來的路徑 ctx.strokeText('shuju') ctx.font="48pxserif"; ctx.textBaseline="hanging"; ctx.strokeText("Helloworld",0,100); console.log(ctx,'----------畫圖函式呼叫成功') ctx.draw();//繪製背景圖片 }, fail:function(err){ console.log(err) } }) },

新增圖片本地圖片:

wxml檔案中:

<canvas canvas-id="canvas" style="border:1px solid #f00;height: 400rpx; width: 400rpx;"></canvas>

js檔案中:

onShow:function(){ constctx=wx.createCanvasContext('canvas'); letwidth=400; letheight=400; letbgPicturePath='../../img/天然氣.jpg';//圖片路徑不要出錯 ctx.drawImage(bgPicturePath,0,0,width,height); ctx.strokeText('shuju') ctx.font="48pxserif"; ctx.textBaseline="hanging"; ctx.strokeText("Helloworld",0,100); console.log(ctx,'----------畫圖函式呼叫成功') ctx.draw();//繪製背景圖片 },

在html插入圖片:

hrml程式碼:

<canvas id="canvas" style="border:1px solid #f00;"></canvas>

js程式碼:

        window.onload=function(){
            draw()
        }
        function draw() {
            var ctx = document.getElementById('canvas').getContext('2d');
            var img = new Image();
            img.onload 
= function(){ ctx.drawImage(img,0,0); ctx.beginPath(); ctx.moveTo(30,96); ctx.lineTo(70,66); ctx.lineTo(103,76); ctx.lineTo(170,15); ctx.stroke(); } console.log('------------這是圖片') img.src = 'http://chuantu.xyz/t6/741/1605489019x2073447983.png'; }