
這里的要注意
getImageData //getImageData() 方法返回 ImageData 對象,該對象拷貝了畫布指定矩形的像素數(shù)據(jù)。
putImageData
//putImageData() 方法將圖像數(shù)據(jù)(從指定的 ImageData 對象)放回畫布上。
context.save() 設(shè)置繪圖環(huán)境存檔
context.restore() 讀取繪圖環(huán)境存檔
var canvas=document.getElementById("canvas"),
context=canvas.getContext("2d"),
eraseAllButton=document.getElementById("eraseAllButton"),
strokeStyleSelect=document.getElementById("strokeStyleSelect"),
guidewireCheckbox=document.getElementById("guidewireCheckbox"),
drawingSurfaceImageData,
mousedown={},
rubberbandRect={},
dragging=false,
guidewires=guidewireCheckbox.checked;
function windowToCanvas(x,y){
var bbox=canvas.getBoundingClientRect()//getBoundingClientRect 返回元素的6個值 left top right bottom width height
return {
x:x-bbox.left*(canvas.width/bbox.width),
y:y-bbox.top*(canvas.height/bbox.height)
}
}
function saveDrawingSurface(){
drawingSurfaceImageData=context.getImageData(0,0,canvas.width,canvas.height)
//getImageData() 方法返回 ImageData 對象,該對象拷貝了畫布指定矩形的像素數(shù)據(jù)。
}
function restoreDrawingSurface(){
context.putImageData(drawingSurfaceImageData,0,0)
//putImageData() 方法將圖像數(shù)據(jù)(從指定的 ImageData 對象)放回畫布上。
}
function updateRubberbandRectangle(loc){
rubberbandRect.width=Math.abs(loc.x-mousedown.x) //用絕對值求線段的長度
rubberbandRect.height=Math.abs(loc.y-mousedown.y) //用絕對值求線段的高度
if(loc.x>mousedown.x){rubberbandRect.left=mousedown.x}else{
rubberbandRect.left=loc.x
}
if(loc.y>mousedown.y){rubberbandRect.top=mousedown.y}else{
rubberbandRect.top=loc.y
}
}
function drawRubberbandShape(loc){
context.beginPath()
context.moveTo(mousedown.x,mousedown.y)
context.lineTo(loc.x,loc.y)
context.stroke()
}
function updataRubberband(loc){ //loc是鼠標點在canvas上的坐標集合對象
// updateRubberbandRectangle(loc)
drawRubberbandShape(loc)
}
//這三個函數(shù)式輔助線函數(shù)
function drawHorizontalLine(y){
context.beginPath()
context.moveTo(0,y+0.5)
context.lineTo(context.canvas.width,y+0.5)
context.stroke()
}
function drawVerticalLine(x){
context.beginPath()
context.moveTo(x+0.5,0)
context.lineTo(x+0.5,context.canvas.height)
context.stroke()
}
function drawGuidewires(x,y){
context.save()
context.strokeStyle="rgba(0,0,230,0.4)"
context.lineWidth=0.5;
drawVerticalLine(x)
drawHorizontalLine(y)
context.restore()
}
//這三個函數(shù)式輔助線函數(shù)
canvas.onmousedown=function(e){ //只執(zhí)行一次
var loc=windowToCanvas(e.clientX,e.clientY); //獲取鼠標點在canvas的點坐標
e.preventDefault();
saveDrawingSurface() //復(fù)制canvas畫布的像素
mousedown.x=loc.x; //鼠標點擊的x軸坐標 這里mousedown記錄的是初始位置
mousedown.y=loc.y; //鼠標點擊的y軸坐標 這里mousedown記錄的是初始位置
dragging=true;
}
canvas.onmousemove=function(e){
var loc;
if(dragging){
e.preventDefault()
loc=windowToCanvas(e.clientX,e.clientY);
restoreDrawingSurface()
updataRubberband(loc) //loc是鼠標點在canvas上的坐標集合對象
if(guidewires){ //輔助線
drawGuidewires(loc.x,loc.y)
}
}
}
canvas.onmouseup=function(e){
loc=windowToCanvas(e.clientX,e.clientY)
restoreDrawingSurface()
updataRubberband(loc)
dragging=false
}
strokeStyleSelect.onchange=function(){
context.strokeStyle=strokeStyleSelect.value
}