您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

HTML5 canvas平铺的代码详解

2024/11/15 4:17:04发布28次查看
最近在做个网站项目,用到很多canvas,有个需求是drawimage把图片画在canvas里面,图片比较小,需要平铺效果,当背景图。ps(背景图高宽10px,需要画的画布高宽200px)
由于一开始是drawimage出来的,所以采用了方法one
var canvas = document.getelementbyid("canvasid"); var ctx = canvas.getcontext("2d"); var img = new image(); //需要平铺的图片 img.src = "test1_bg.jpg"; img.onload = function (){ var can = document.createelement("canvas"); can.width = 10; can.height = 10; var ctx2 = can.getcontext("2d"); ctx2.drawimage(img,0,0,10,10,0,0,10,10); ctx.fillstyle = ctx.createpattern(can,"repeat"); ctx.fillrect(0,0,200,200); }
用到了背景图的高宽度10,有点繁琐,为什么不一步到位呢?所以改成了这种方式
var canvas = document.getelementbyid("canvasid"); var ctx = canvas.getcontext("2d"); var img = new image(); //需要平铺的图片 img.src = "test1_bg.jpg"; img.onload = function (){ var pat = ctx.createpattern(img,"repeat"); ctx.rect(0,0,200,200); ctx.fillstyle = pat; ctx.fill(); }
good!
再来重申下createpattern定义
createpattern() 方法在指定的方向内重复指定的元素。
元素可以是图片、视频,或者其他 <canvas> 元素。
被重复的元素可用于绘制/填充矩形、圆形或线条等等。
javascript 语法:
context.createpattern(image,"repeat|repeat-x|repeat-y|no-repeat");
参数 描述
repeat 默认。规定要使用的图片、画布或视频元素。
repeat-x 该模式只在水平方向重复。
repeat-y 该模式只在垂直方向重复。
no-repeat 该模式只显示一次(不重复)。
以上就是html5 canvas平铺的代码详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product