先放镇楼图 ~~吸引火力
canvas真是一个灰常有意思的东西,
在原来橡皮筋式线段绘制的基础上实现的,由橡皮筋线段的始末两点构成矩形,
根据橡皮筋线段的颜色绘制不同颜色的矩形
注意:
这里的颜色变换只加入了两种颜色 ,根据起始端点的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;
}