在做微信小游戏的时候,需要在开放域绘制页面,而且不是固定大小的底,这就不得不,用九宫格绘制页面底了
1. 原理:
就不多说了
2. 代码
//代码可以复制到w3 这里去测试
//https://www.w3school.com.cn/tiy/t.asp?f=eg_html5_canvas_image
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("scream");
var rect = {
x:45,
y:50,
width:220,
height:124,
}
var imgeSize = {
width:300,
height :227
}
var target ={
x : 10,
y:10,
width:700,
height:500
}
function draw(imageSize,rect, target){
var sp13X = rect.x + rect.width;
var sw34 = imageSize.width - sp13X;
var sp31Y = rect.y + rect.height;
var sh34 = imageSize.height - sp31Y;
var dp13X = target.x+target.width - sw34
var dp31Y = target.y+target.height - sh34
var dp22X = target.x+ rect.x
var dp22Y = target.y+ rect.y
var dw23 = dp13X - dp22X
var dh23 = dp31Y - dp22Y
//角1
ctx.drawImage(img, 0, 0, rect.x, rect.y, target.x, target.y, rect.x, rect.y);
//角2
ctx.drawImage(img, sp13X, 0, sw34, rect.y, dp13X, target.y, sw34, rect.y);
//角3
ctx.drawImage(img, 0, sp31Y, rect.x, sh34, target.x, dp31Y, rect.x, sh34);
//角4
ctx.drawImage(img, sp13X, sp31Y, sw34, sh34, dp13X, dp31Y, sw34, sh34);
//中
ctx.drawImage(img, rect.x, rect.y, rect.width, rect.height, dp22X, dp22Y, dw23, dh23);
//中12
ctx.drawImage(img, rect.x, 0, rect.width, rect.y, dp22X, target.y, dw23, rect.y);
//中21
ctx.drawImage(img, 0, rect.y, rect.x, rect.height, target.x, dp22Y, rect.x, dh23);
//中23
ctx.drawImage(img, sp13X, rect.y, sw34, rect.height, dp13X, dp22Y, sw34, dh23);
//中32
ctx.drawImage(img, rect.x, sp31Y, rect.width, sh34, dp22X, dp31Y, dw23, sh34);
}
draw(imgeSize,rect,target)