摘要:本篇教程探讨了HTML5+CSS3从入门到精通 canvas绘制爱心的2种方法,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 。
本篇教程探讨了HTML5+CSS3从入门到精通 canvas绘制爱心的2种方法,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 。
<
第一种方法:桃心形公式
代码实现的一种方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用桃心形方程绘制爱心</title>
</head>
<body>
<canvas></canvas>
<script>
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var Heart = function(ctx, x, y, a) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.a = a;
this.vertices = [];
for(let i=0; i<50; i++) {
var step = i/50*(Math.PI*2);//设置心上面两点之间的角度,具体分成多少份,好像需要去试。
var vector = {
x : this.a*(16 * Math.pow(Math.sin(step), 3)),
y : this.a*(13 * Math.cos(step) - 5 * Math.cos(2 * step) - 2 * Math.cos(3 * step) - Math.cos(4 * step))
}
this.vertices.push(vector);
}
}
Heart.prototype.draw = function() {
this.ctx.beginPath();
this.ctx.translate(this.x,this.y);
this.ctx.rotate(Math.PI);
for(let i=0; i<50; i++) {
var vector = this.vertices[i];
this.ctx.lineTo(vector.x, vector.y);
}
this.ctx.fillStyle = "red";
this.ctx.fill();
}
canvas.onmousedown = function(e) {
var x = e.offsetX;
var y = e.offsetY;
var a = 6;
var heart = new Heart(ctx, x, y, a);
heart.draw();
}
</script>
</body>
</html>
第二种方法:笛卡尔的心形线
代码实现的一种方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用笛卡尔心形线方程绘制爱心</title>
</head>
<body>
<canvas></canvas>
<script>
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function Heart(ctx, x, y, a) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.a = a;
this.draw = function() {
this.ctx.beginPath();
this.ctx.translate(this.x, this.y);
this.ctx.rotate(Math.PI);
var start = 0;
for(var i=0; i<500; i++) {
start += Math.PI*2/500;
var end = start+Math.PI*2/500;
var r = this.a*(1-Math.sin(start));
ctx.arc(0, 0, r, start, end, false);
}
ctx.fillStyle = "red";
ctx.fill();
}
}
canvas.onmousedown = function(e) {
var x = e.offsetX;
var y = e.offsetY;
var a = 60;
var heart = new Heart(ctx, x, y, a);
heart.draw();
}
</script>
</body>
</html>
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标WEB前端HTML5/CSS3频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号