/* 期望效果: * 在鼠標點擊位置繪制圖形--心形 * * 錯誤做法: (引以為戒。。。) * 使用canvas API中的translate,分別以鼠標點擊位置的offsetX、offsetY為畫布坐標的水平和豎直方向的偏移量,繪制圖形,但實際效果和預期完全不太一樣(大哭~~~) * * 錯誤原因: * translate是以上個坐標原點為基礎,進行平移 (原諒我的無知~~~~~) * * 解決問題: * 在開始繪制前,將當前狀態使用save()保存下來,並在每一次繪制結束之后,使用restore()將狀態重置,以免影響下次點擊(原理上用鼠標點擊位置減去畫布上次的原點位置應該也可以,但是比較繁瑣) * * 最后吐槽下: * 有很多文章在介紹相同效果的繪制,但是真的有自測過嗎。。。
* 記得去年自己還有用canvas畫過挺炫酷餅狀圖來着,( ⊙ o ⊙ )果然作為一枚渣渣還得老老實實的板磚敲代碼啊~~) */
所用極坐標方程:

注:本篇博客只是對所做demo的記錄總結
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>heart--equation</title>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<!-- 默認寬高300*150 -->
<!-- style方式設置canvas寬高會在默認寬高的基礎上進行拉伸,導致變形 -->
<canvas></canvas> </body> <script> (function(win) { let Heart = function(ctx, x, y, size) { this.ctx = ctx; this.x= x; this.y = y; this.size = size; this.vertices = getVector(); function getVector() { let vertices = []; // console.log(this == win) //true for(let i = 0; i < 50; i++) { let step = i/50 * (Math.PI * 2); let vector = { x : size * (16 * Math.pow(Math.sin(step), 3)), y : size * (13 * Math.cos(step) - 5 * Math.cos(2 * step) - 2 * Math.cos(3 * step) - Math.cos(4 * step)) } vertices.push(vector); } return vertices; }; } Heart.prototype.draw = function() { this.ctx.save(); this.ctx.beginPath(); this.ctx.translate(this.x, this.y); this.ctx.rotate(Math.PI); let vertices = this.vertices for(let i = 0; i < vertices.length; i++) { let vector = vertices[i]; this.ctx.lineTo(vector.x, vector.y); } // this.ctx.fillStyle = 'hotpink'; // this.ctx.fill(); this.ctx.strokeStyle = "hotpink"; this.ctx.stroke(); this.ctx.closePath(); this.ctx.restore(); }; win.Heart = Heart; })(window) </script> <script> let canvas = document.querySelector('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; let ctx = canvas.getContext('2d'); canvas.onclick = function(e) { let size = 6; let x = e.offsetX; let y = e.offsetY; let heart = new Heart(ctx, x, y, size); heart.draw(); } </script> </html>
2019-01-11~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~已實踐
