canvas绘制两点渐变图,以及如何自适应窗口大小

css代码:

        * {
        margin: 0;
        padding: 0;
        }
        html, body {
        width: 100%;
        height: 100%;
        overflow-y: hidden;
        }
        canvas {
        display: block;
        }

html代码:

 <div style="width: 100%;" id="content">
        <canvas id="canvas" width="800" height="600">
            我画不了
        </canvas>
    </div>

js代码:

const colorA={r:124,g:255,b:223},colorB={r:254,g:179,b:229}
        const canvas=document.getElementById('canvas')
        function draw(){
            var contentWidth = document.getElementById('content').clientWidth
            var contentHeight = document.getElementById('content').clientHeight
            canvas.width = contentWidth
            canvas.height = contentHeight
            console.log( canvas.width,canvas.height);
            if(!canvas.getContext)return;
            var ctx=canvas.getContext("2d")
            for(var i=0;i<canvas.width;i++){
                for(var j=0;j<canvas.height;j++){
                    ctx.fillStyle = 'rgb(' +Math.floor(colorA.r*((canvas.width+canvas.height)-i-j)/(canvas.width+canvas.height)+colorB.r*(i+j)/(canvas.width+canvas.height) )+ ',' +
                    Math.floor(colorA.g*((canvas.width+canvas.height)-i-j)/(canvas.width+canvas.height)+colorB.g*(i+j)/(canvas.width+canvas.height))+ ','+
                    Math.floor(colorA.b*((canvas.width+canvas.height)-i-j)/(canvas.width+canvas.height)+colorB.b*(i+j)/(canvas.width+canvas.height))+')';
                    ctx.fillRect(i, j, 1, 1);
                }
            }
        }
        draw()
        window.onresize = function () {
            draw()
        }

colorA和colorB是你要选择的颜色,默认是铺平整个屏幕。

通过获取浏览器窗口的高和宽,设置给canvas。

两次for循环绘制两点渐变图。

window.onresize事件监听,当窗口大小发生改变则调用函数draw()。 

效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值