内容简介:指画图时橡皮筋一样伸缩自如。。例子如下:point_down:
什么叫橡皮筋式
指画图时橡皮筋一样伸缩自如。。
例子如下:point_down:
思路
思路很简单,只有橡皮筋式绘制功能要注意,以下总结mousedown,mousemove,mouseup三个阶段的思路
mousedown:记录start位置,drag(记录是否处于拖动状态)设置为true,getImageData( 橡皮筋效果关键1
)
mousemove:获取拖动时的位置pos,putImageData( 对应getImageData,橡皮筋效果关键2
),根据pos与start画直线
mouseup:drag恢复为false
关键
就在于putImageData()与getImageData()这两个canvas的方法,putImageData()记录了鼠标点下时的图像,getImageData()对应还原。如果没有执行这两个方法就会出现以下的效果
putImageData()相当于把“扫描”出来的线都擦掉
代码
<canvas id="canvas" width="600" height="400" style="border: 1px solid black;"> </canvas> <script type="text/javascript"> let canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), canvasLeft = canvas.getBoundingClientRect().left, //getBoundingClientRect()获取元素位置 canvasTop = canvas.getBoundingClientRect().top; let imageData; //记录图像数据 let start = new Map([['x',null],['y',null]]); let drag = false;//记录是否处于拖动状态 canvas.onmousedown = function (e) { let pos = positionInCanvas(e, canvasLeft, canvasTop); start.set('x', pos.x); start.set('y', pos.y); drag = true; //记录imageData imageData = ctx.getImageData(0,0,canvas.width,canvas.height); } canvas.onmousemove = function (e) { if(drag === true){ let pos = positionInCanvas(e, canvasLeft, canvasTop); //相当于把扫描出来的线都擦掉,重新画 ctx.putImageData(imageData, 0, 0); ctx.beginPath(); ctx.moveTo(start.get('x'), start.get('y')); ctx.lineTo(pos.x, pos.y); ctx.stroke(); } } canvas.onmouseup = function (e) { drag = false; } function positionInCanvas (e, canvasLeft, canvasTop) {//获取canvas中鼠标点击位置 return { x:e.clientX - canvasLeft, y:e.clientY - canvasTop } } </script>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Starfish and the Spider
Ori Brafman、Rod A. Beckstrom / Portfolio Hardcover / 2006-10-05 / USD 24.95
Understanding the amazing force that links some of today's most successful companies If you cut off a spider's leg, it's crippled; if you cut off its head, it dies. But if you cut off a st......一起来看看 《The Starfish and the Spider》 这本书的介绍吧!