什么叫橡皮筋式
指画图时橡皮筋一样伸缩自如。。例子如下????
思路
思路很简单,只有橡皮筋式绘制功能要注意,以下总结 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>