本文主要是介绍canvas绘制小树阴影-transform,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
绘制小路,可用quadraticCurveTo(二次贝塞尔曲线)来绘制复杂曲线,也可以用bezierCurveTo(三次贝塞尔曲线)。
效果图
代码如下:
demo.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>canvas {border: 1px solid red;}</style>
</head><body><canvas id="mycanvas" width="800" height="600">你的浏览器不支持!</canvas>
</body>
<script src="demo1.js"></script></html>
demo.js
var canvas, ctx;
canvas = document.getElementById("mycanvas");
ctx = canvas.getContext("2d");function Init() {drawPath();shadow(310, 300);drawTree(150, 80);shadow(800, 570);drawTree(500, 350);}
// 小路
function drawPath() {ctx.beginPath();ctx.save();ctx.translate(-10, 550);ctx.moveTo(0, 0);ctx.quadraticCurveTo(170, 50, 360, -250);ctx.quadraticCurveTo(360, -320, 820, -420);ctx.strokeStyle = '#663300';ctx.lineWidth = 40;ctx.stroke();ctx.restore();
}
// 画小树
function drawTree(x, y) {ctx.save();ctx.beginPath();ctx.moveTo(x, y);ctx.lineTo(x + 60, y + 60);ctx.lineTo(x + 20, y + 60);ctx.lineTo(x + 80, y + 120);ctx.lineTo(x + 20, y + 120);ctx.lineTo(x + 100, y + 180);ctx.lineTo(x - 100, y + 180);ctx.lineTo(x - 20, y + 120);ctx.lineTo(x - 80, y + 120);ctx.lineTo(x - 20, y + 60);ctx.lineTo(x - 60, y + 60);ctx.closePath();// 线宽ctx.lineWidth = 4;//平滑路径的接合点ctx.lineJoin = 'round';//将颜色改成棕色ctx.strokeStyle = '#663300';//将这条线绘制到canvas上ctx.stroke();//将填充色设置为绿色并填充ctx.fillStyle = '#339900';ctx.fill();//将填充色设为棕色ctx.fillStyle = '#663300';//填充用作树干的矩形区域ctx.fillRect(x - 10, y + 180, 20, 60);ctx.restore();
}
// 小树阴影
function shadow(x, y) {ctx.save();var m = 100,n = 30,l = 120; //m为树干高,n为树枝高,l为树面积半径ctx.transform(1, 0, -0.5, 1, 0, 0);ctx.beginPath();ctx.moveTo(x, y);ctx.lineTo(x + 10, y);ctx.lineTo(x + 10, y - m);ctx.lineTo(x + l, y - m);ctx.lineTo(x + 20, y - m - n);ctx.lineTo(x + l / 2, y - m - n);ctx.lineTo(x + 20, y - m - 2 * n);ctx.lineTo(x + l / 4, y - m - 2 * n);ctx.lineTo(x, y - m - 3 * n);ctx.lineTo(x - l / 4, y - m - 2 * n);ctx.lineTo(x - 20, y - m - 2 * n);ctx.lineTo(x - l / 2, y - m - n);ctx.lineTo(x - 20, y - m - n);ctx.lineTo(x - l, y - m);ctx.lineTo(x - 10, y - m);ctx.lineTo(x - 10, y);ctx.closePath();ctx.scale(1, 0.5); //放缩ctx.fillStyle = "rgba(0,0,0,0.2)"; //透明度20%黑色ctx.fill();ctx.restore();
}
window.addEventListener("load", Init, false)
这篇关于canvas绘制小树阴影-transform的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!