利用canvas繪製愛心
阿新 • • 發佈:2018-12-10
需求:繪製愛心影象軌跡。實現:直接貼程式碼吧!預覽地址:繪製愛心影象軌跡
<!DOCTYPE> <html> <head> <meta charset="UTF-8"> <title>模仿筆畫</title> <style type="text/css"> #_canvas { background-color: rgb(240, 240, 240); border: 1px solid #000; } </style> </head> <body> <canvas id="_canvas" width="500" height='500'>sorry, your broswer does not support html5!</canvas> <script type="text/javascript"> var canvas_ = document.getElementById("_canvas"); var context = canvas_.getContext("2d"); //線條設定 context.strokeStyle = "red"; context.lineWidth = 2; //線條陣列 var array_paint = []; //背景圖 var img = new Image() img.src = "https://ws1.sinaimg.cn/large/0065nu1aly1fv5kg78i8kj30xc0m8ank.jpg" context.drawImage(img, 0, 0); function paint() { context.beginPath(); context.moveTo(array_paint[0][0], array_paint[0][1]); if (array_paint.length == 1) context.lineTo(array_paint[0][0] + 1, array_paint[0][1] + 1); else { var i = 1; for (i in array_paint) { context.lineTo(array_paint[i][0], array_paint[i][1]); context.moveTo(array_paint[i][0], array_paint[i][1]); } } context.closePath(); context.stroke(); } let num = -1; let timer = null; let list = [] //建立座標 list = heartShape(20, 50, 20) function people() { num++; var imgpeople = new Image() imgpeople.src = "https://ws1.sinaimg.cn/large/0065nu1aly1fvcmafdhe6j305k05k3ye.jpg" context.drawImage(imgpeople, list[num].current_x * 500 / 100 - 10, list[num].current_y * 500 / 100 - 20, 20, 20); context.clearRect(0, 0, screen.width, screen.height); context.drawImage(img, 0, 0); console.log(list[num].current_x * 500 / 100); if (num < list.length - 1) { let current_x = (Math.random() * 100).toFixed(2); let current_y = (Math.random() * 100).toFixed(2); array_paint.push([list[num].current_x * 500 / 100, list[num].current_y * 500 / 100]); paint(); if (num > 0) { context.drawImage(imgpeople, list[num].current_x * 500 / 100 - 10, list[num].current_y * 500 / 100 - 20, 20, 20); } } else { array_paint = []; for (var i = 0; i < list.length; i++) { array_paint.push([list[i].current_x * 500 / 100, list[i].current_y * 500 / 100]); paint(); context.drawImage(imgpeople, list[num].current_x * 500 / 100 - 10, list[num].current_y * 500 / 100 - 20, 20, 20); } clearInterval(timer); } } timer = setInterval(people, 50) function heartShape(r, dx, dy) { //r:大小;dx:水平偏移;dy:垂直偏移;c:顏色 var m, n, x, y, i; let arr = []; for (i = 0; i <= 7.9; i += 0.04) { m = i; n = -r * (((Math.sin(i) * Math.sqrt(Math.abs(Math.cos(i)))) / (Math.sin(i) + 1.4)) - 2 * Math.sin(i) + 2); x = n * Math.cos(m) + dx; y = n * Math.sin(m) + dy; arr.push({ current_x: x, current_y: y }) } return arr } </script> </body> </html>