70行代码绘制canvas圣诞树:无需引入图片和外部文件
Posted 前端呆头鹅
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了70行代码绘制canvas圣诞树:无需引入图片和外部文件相关的知识,希望对你有一定的参考价值。
圣诞节刚刚过去,送给大家一株迟来的圣诞树。
该圣诞树由纯canvas绘制而成,不引入任何图片和外部文件。
超过30人收藏,添加详细教程。
(是的,只要30人收藏即可,30个收藏就能解锁详细教程,快动动小手吧)
效果图:
<body>
<canvas id="canvas" style="background-color:#cfd7c1" width="670" height="380"></canvas>
</body>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const data =
start: [
[400, 300], [370, 310], [340, 305], [310, 300], [280, 300],
[365, 290], [365, 284], [335, 288], [305, 288], [275, 288],
[370, 275], [360, 280], [330, 280], [300, 278],
[385, 270], [355, 265], [325, 268], [295, 270], [250, 280],
[380, 260], [350, 263], [320, 258], [290, 258],
[370, 248], [345, 248], [315, 248], [285, 248],
[340, 238], [340, 238], [310, 238],
[360, 225], [335, 225], [305, 225],
[350, 213], [340, 213], [310, 213], [370, 213],
[335, 200], [327, 200], [313, 200], [295, 200],
[340, 188], [325, 190], [315, 190],
[340, 170], [335, 180], [310, 180], [280, 180],
[340, 155], [335, 159], [310, 167],
[340, 140], [335, 145], [310, 155],
[340, 130], [335, 135], [310, 135],
]
const color = ["#2d5419", "#417c24", "#57a431", "#438124"]
function drawTree(startX, startY, angle, length)
console.log(angle)
ctx.beginPath();
ctx.moveTo(startX, startY);
const angltData = angle.shift()
const lengthData = length[0]
endX = startX + Math.cos(angltData)*lengthData;
endY = startY + Math.sin(angltData)*lengthData;
ctx.lineTo(endX, endY);
ctx.strokeStyle = color[angle.length];
ctx.lineWidth = 3.5;
ctx.stroke();
if(angle.length)
drawTree(startX, startY, angle, length)
else if(length.length)
drawTree(startX, startY, angle: [-0.5, -1.5, -2.5, -3.5], length: length.slice(1))
function drawStar()
ctx.beginPath();
ctx.moveTo(330, 120);
ctx.strokeStyle = "#438124"
ctx.arc(330, 70, 15, 90*Math.PI/180,500*Math.PI/180)
ctx.closePath();
ctx.stroke();
function drawgift(x, y, fillStyle, strokeStyle, width)
ctx.beginPath();
ctx.strokeStyle = strokeStyle;
ctx.fillStyle = fillStyle;
ctx.lineWidth = 5;
ctx.lineJoin = 'round'
ctx.fillRect(x, y, width, width);
ctx.strokeRect(x, y, width, width);
ctx.closePath();
ctx.stroke();
drawgiftLine(x, y, width)
function drawgiftLine(x, y, width)
ctx.beginPath();
ctx.moveTo(x+width/3, y);
ctx.lineTo(x+width/3, y+width)
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x+width/3*2, y);
ctx.lineTo(x+width/3*2, y+width)
ctx.stroke();
drawgift(170, 200, "#57a431", "#417c24", 80)
drawgift(150, 240, "#ccf83f", "#a5ce99", 50)
for(item of data.start)
drawTree(startX: item[0], startY: item[1], angle: [0, -1, -2, -3], length: [30,25])
drawStar()
</script>
以上是关于70行代码绘制canvas圣诞树:无需引入图片和外部文件的主要内容,如果未能解决你的问题,请参考以下文章