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()。
效果图: