canvas createPattern()
createPattern()方法可以建立一種模式,用於規定在指定方向重複指定元素。
通俗的講,所謂模式就是一種規則,指定元素重複方式的規則。
被重複的元素可以是圖片、視訊,或者其他<canvas>元素等。
此方法返回CanvasPattern型別物件,可以用於圖案的填充或者描邊。
語法結構:
[JavaScript] 純文字檢視 複製程式碼context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");
引數解析:
(1).image:規定要使用模式的圖片、畫布或視訊元素。
(2).repeat:規定模式在水平和垂直方向重複,預設值。
(3).repeat-x:規定模式只在水平方向重複。
(4).repeat-y:規定模式只在垂直方向重複。
(5).no-repeat:規定模式不重複。
瀏覽器相容:
(1).IE9+瀏覽器支援此方法。
(2).edge瀏覽器支援此方法。
(3).谷歌瀏覽器支援此方法。
(4).火狐瀏覽器支援此方法。
(5).Opera瀏覽器支援此方法。
(6).Safari瀏覽器支援此方法。
程式碼例項如下:
[HTML] 純文字檢視 複製程式碼執行程式碼<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>螞蟻部落</title> <style> canvas{ border:1px solid black; } </style> <script> let draw=(direction)=>{ let cvs=document.getElementById("ant"); let ctx=cvs.getContext("2d"); ctx.clearRect(0,0,cvs.width,cvs.height); let img=document.getElementById("lamp") let pat=ctx.createPattern(img,direction); ctx.rect(0,0,150,100); ctx.fillStyle=pat; ctx.fill(); } window.onload = () => { let btR=document.getElementById("r"); let btX=document.getElementById("x"); let btY=document.getElementById("y"); let btN=document.getElementById("n"); btR.onclick=function(){draw('repeat')} btX.onclick=function(){draw('repeat-x')} btY.onclick=function(){draw('repeat-y')} btN.onclick=function(){draw('no-repeat')} } </script> </head> <body> <canvas id="myCanvas">當前瀏覽器不支援canvas標籤</canvas> <br/> <img src="demo/html5/img/img_lamp.jpg" id="lamp"> <button id="r">Repeat</button> <button id="x">Repeat-x</button> <button id="y">Repeat-y</button> <button id="n">No-repeat</button> </body> </html>
程式碼執行效果截圖如下:
點選底部幾個按鈕可以演示"燈泡"圖片以何種模式進行重複。
上述程式碼核心部分進行簡單分析:
(1).通過clearRect()方法對之前的畫布進行擦除,否則之前的圖案會有存留,無法正確演示。
(2).let pat=ctx.createPattern(img,direction),建立一個指定圖片的重複模式,是CanvasPattern型別。
(3).返回的CanvasPattern物件物件可以作為圖案的填充或者描邊。
相關文章
- 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 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
- canvas toDataURL()Canvas
- canvas toBlob()Canvas