1.需求:用图片填充canvas画布,并且能控制图片的大小和重复次数,实现的效果如下:
2.HTML代码实现
1 <html> 2 <head> 3 <title></title> 4 <meta charset="utf-8" /> 5 <style> 6 #canvas{ 7 width: 300px; 8 height: 300px; 9 margin: 100px 0 0 200px; 10 border: 1px solid #f00; 11 } 12 </style> 13 </head> 14 <body> 15 <canvas id="canvas" width="500" height="500"></canvas> 16 <script src="bgImage.js"></script> 17 </body> 18 </html>
3.JavaScript代码
1 var canvas = document.getElementById("canvas"); 2 var ctx = canvas.getContext("2d"); 3 canvas.width = 300; 4 canvas.height = 300; 5 var img = new Image(50, 50); 6 img.src = 't3.png'; 7 img.onload = function() { 8 //先把加载好的图片绘制在一个临时的画布上 9 let tempCanvas = document.createElement('canvas'); 10 tempCanvas.width = 50; 11 tempCanvas.height = 50; 12 let tempCtx = tempCanvas.getContext('2d'); 13 tempCtx.drawImage(img, 0, 0, this.width, this.height); 14 // 创建一个绘制背景图的模式 15 let pattern = ctx.createPattern(tempCanvas, 'repeat'); 16 ctx.fillStyle = pattern; 17 ctx.fillRect( 0, 0, canvas.width, canvas.height); 18 };
3.注意点:
(1)canvas.width 与css的width不同,canvas.width是画布的逻辑像素,
画布内的尺寸是canvas.width和canvas.height决定的,
css的width,height只能缩放canvas画布大小
(2)只有把加载的图片绘制一个临时的canvas上,才能方便的控制重复单元的大小
4.参考链接:
(1)createPattern的使用:https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/createPattern
(2)canvas.width属性和canvas的css样式width的区别:https://blog.csdn.net/css_666/article/details/105202622
标签:canvas,height,画布,width,tempCanvas,createPattern,图片大小 From: https://www.cnblogs.com/xiaoyuxielikebai/p/16926578.html