JavaScipt30(第八个案例)(主要知识点:canvas)
生活随笔
收集整理的這篇文章主要介紹了
JavaScipt30(第八个案例)(主要知识点:canvas)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
承接上文,這是第8個案例,要實現的效果是按住鼠標不放,進行拖動時可以在畫布上畫出不同粗細不同顏色的曲線。
附上項目鏈接:?https://github.com/wesbos/JavaScript30
主要思路:鼠標按下時,記錄當前x,y坐標,作為起點,鼠標移動時開始畫線。鼠標左鍵抬起或移出畫布時停止繪畫。沒什么講的,有個值得注意的點,hsl這個表現顏色,我之前不知道的。附上源碼:
<script>const canvas = document.querySelector('#draw');const ctx = canvas.getContext('2d');canvas.width = window.innerWidth;canvas.height = window.innerHeight;ctx.strokeStyle = '#BADA55';ctx.lineJoin = 'round';ctx.lineCap = 'round';ctx.lineWidth = 100;// ctx.globalCompositeOperation = 'multiply'; let isDrawing = false;let lastX = 0;let lastY = 0;let hue = 0;let direction = true;function draw(e) {if (!isDrawing) return; // stop the fn from running when they are not moused down console.log(e); // HSL(H,S,L),css3顏色值表示方式, // H:Hue(色調)。0(或360)表示紅色,120表示綠色,240表示藍色,也可取其他數值來指定顏色。取值為:0 - 360 // S:Saturation(飽和度)。取值為:0.0% - 100.0% // L:Lightness(亮度)。取值為:0.0% - 100.0%ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;ctx.beginPath();// start from ctx.moveTo(lastX, lastY);// go to ctx.lineTo(e.offsetX, e.offsetY);ctx.stroke();[lastX, lastY] = [e.offsetX, e.offsetY];hue++;if (hue >= 360) {hue = 0;}if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {direction = !direction;}if (direction) {ctx.lineWidth++;} else {ctx.lineWidth--;}}canvas.addEventListener('mousedown', (e) => {isDrawing = true;[lastX, lastY] = [e.offsetX, e.offsetY];});canvas.addEventListener('mousemove', draw);canvas.addEventListener('mouseup', () => isDrawing = false);canvas.addEventListener('mouseout', () => isDrawing = false);</script>?
轉載于:https://www.cnblogs.com/wangxi01/p/10648612.html
總結
以上是生活随笔為你收集整理的JavaScipt30(第八个案例)(主要知识点:canvas)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows下安装及使用NVM
- 下一篇: 联想电脑小新潮(联想电脑小新潮7000怎