Canvas 画九宫格图片

在做微信小游戏的时候,需要在开放域绘制页面,而且不是固定大小的底,这就不得不,用九宫格绘制页面底了

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值