canvaspattern canvasrenderingcontext2d.createpattern(image | canvas image, string repetition)
基础库 或更高版本; 若版本较低,建议采取 兼容处理 。
支小宝客户端 支持
安诊儿客户端 支持
主体: 企业支付宝小程序 、 个人支付宝小程序
使用指定的元图像创建图案。
效果示例
代码示例执行效果
元图像
创建的图案
image | canvas image
元图像。客户端 10.5.26 起支持 canvas 类型,将画布作为元图像。
string repetition
如何重复图像。可选,默认值为repeat
。
将图片作为元图像
将另一个画布作为元图像
.js
.axml
page({
oncanvasready() {
// 获取画布 1
my.createselectorquery().select('#canvas').node().exec((res) => {
this.canvas = res[0].node
this.ctx = this.canvas.getcontext('2d')
// 获取画布 2
my.createselectorquery().select('#canvas2').node().exec((res) => {
this.canvas2 = res[0].node
this.ctx2 = this.canvas2.getcontext('2d')
this.draw()
})
})
},
draw() {
let img = this.canvas.createimage()
img.src = 'https://mdn.alipayobjects.com/huamei_esgcm9/afts/img/a*obkbr4bfxbeaaaaaaaaaaaaadsajaq/original'
img.onload = () => {
// 将图片画到画布 1 上
this.ctx.drawimage(img, 0, 0)
// 将画布 1 作为元图像
const pattern = this.ctx2.createpattern(this.canvas, "repeat")
this.ctx2.fillstyle = pattern
this.ctx2.fillrect(0, 0, 300, 300)
}
}
})
<view>
<view>
<canvas
id="canvas"
type="2d"
width="86"
height="117"
style="
width: 86px;
height: 117px
"
onready="oncanvasready"
>canvas>
view>
<canvas id="canvas2" type="2d">canvas>
view>
.js
.axml
page({
oncanvasready() {
// 获取画布 1
my.createselectorquery().select('#canvas').node().exec((res) => {
this.canvas = res[0].node
this.ctx = this.canvas.getcontext('2d')
// 获取画布 2
my.createselectorquery().select('#canvas2').node().exec((res) => {
this.canvas2 = res[0].node
this.ctx2 = this.canvas2.getcontext('2d')
this.draw()
})
})
},
draw() {
let img = this.canvas.createimage()
img.src = 'https://mdn.alipayobjects.com/huamei_esgcm9/afts/img/a*obkbr4bfxbeaaaaaaaaaaaaadsajaq/original'
img.onload = () => {
// 将图片画到画布 1 上
this.ctx.drawimage(img, 0, 0)
// 将画布 1 作为元图像
const pattern = this.ctx2.createpattern(this.canvas, "repeat")
this.ctx2.fillstyle = pattern
this.ctx2.fillrect(0, 0, 300, 300)
}
}
})
<view>
<view>
<canvas
id="canvas"
type="2d"
width="86"
height="117"
style="
width: 86px;
height: 117px
"
onready="oncanvasready"
>canvas>
view>
<canvas id="canvas2" type="2d">canvas>
view>