先放鎮(zhèn)樓圖 ~~吸引火力
canvas真是一個灰常有意思的東西昵观,
在原來橡皮筋式線段繪制的基礎(chǔ)上實現(xiàn)的碳抄,由橡皮筋線段的始末兩點構(gòu)成矩形愉老,
根據(jù)橡皮筋線段的顏色繪制不同顏色的矩形
注意:
這里的顏色變換只加入了兩種顏色 ,根據(jù)起始端點的X軸位移量決定剖效,絕對值用Math.abs即可
var canvas=document.getElementById("canvas")
var context=canvas.getContext("2d");
var canvas_mouse_move={};
var canvas_mouse_obj={};
var save_image_data=null;
var drag=null
var windowToCanvas=function(x1,y1){
var left=canvas.getBoundingClientRect().left;
var top=canvas.getBoundingClientRect().top;
return{
x:x1-left,
y:y1-top
}
}
var save_image=function(){
save_image_data=context.getImageData(0,0,canvas.width,canvas.height)
}
var put_image=function(){
context.putImageData(save_image_data,0,0)
}
canvas.onmousedown=function(e){
var mousedown_left=e.clientX;
var mousedown_top=e.clientY;
save_image()
canvas_mouse_obj=windowToCanvas(mousedown_left,mousedown_top)
drag=true;
}
canvas.onmousemove=function(e){
if(drag){
put_image()
canvas_mouse_move=windowToCanvas(e.clientX,e.clientY)
context.beginPath()
context.moveTo(canvas_mouse_obj.x,canvas_mouse_obj.y)
context.lineTo(canvas_mouse_move.x,canvas_mouse_move.y)
var num_length=Math.abs(canvas_mouse_move.x-canvas_mouse_obj.x)
if(200>num_length>0){context.strokeStyle="red";context.fillStyle="red"}
if(num_length>200){context.strokeStyle="green";context.fillStyle="green"}
context.stroke()
}
}
canvas.onmouseup=function(e){
var endx=e.clientX;
var endy=e.clientY;
var end=windowToCanvas(endx,endy)
context.beginPath()
context.moveTo(canvas_mouse_obj.x,canvas_mouse_obj.y)
context.lineTo(end.x,end.y)
context.stroke()
context.beginPath();
context.rect(canvas_mouse_obj.x,canvas_mouse_obj.y,end.x-canvas_mouse_obj.x,end.y-canvas_mouse_obj.y)
context.fill()
drag=false;
}