[JavaScript] 纯文本查看 复制代码
window.οnlοad=function () {
// 创建画布
var canvas=document.createElement('canvas');
var brush=canvas.getContext("2d");
canvas.style.border="2px solid #aaaaaa";
canvas.width=700;
canvas.height=700;
// 包裹画布居中
var box=document.createElement('div');
// box样式
box.style.width=canvas.width+"px";
box.style.height=canvas.height+"px";
box.style.margin="100px auto";
// 移动块
var move=document.createElement('span');
// move样式
move.style.color="#ff0000";
move.style.position="absolute";
move.style.display="none";
move.style.boxShadow="1px 1px 8px red";
// 添加对象
document.body.appendChild(box);
document.body.appendChild(move);
box.appendChild(canvas);
// 避免重复获取画布大小
var Ox=canvas.offsetLeft;
var Oy=canvas.offsetTop;
move.style.display="none";
function mymove (event) {
move.style.display="block";
move.style.left=event.pageX-50+"px";
move.style.top=event.pageY-50+"px";
move.innerHTML="当前画布坐标:"+(event.clientX-Ox-2)+","+(event.clientY-Oy-2);
}
function myout () {
move.style.display="none";
}
canvas.οnmοusemοve=mymove;
canvas.οnmοuseοut=myout;
brush.translate(350,350);
// var startX=parseInt(Math.random()*660)+20;
// var startY=parseInt(Math.random()*660)+20;
var x=0;//初始坐标
var y=0;//初始坐标
var high=15;//x坐标改变值 不能为负值
var low=10;//y坐标改变值 不能为负值
var state;//执行状态有四个
var target_x;
var target_y;
function action() {
brush.clearRect(-350,-350,700,700);
brush.beginPath();
brush.fillStyle="red";
brush.arc(x,y,20,0,Math.PI*2);
brush.fill();
triangle_x=x-target_x;//偏移量x
triangle_y=y-target_y;//偏移量y
if (x>=330 || state==null) {
if (triangle_x>0 && triangle_y>0) {
state="left_button";
}else if (triangle_x>0 && triangle_y<0){
state="left_top";
}else{
state="right_button";
}
}else if (y>=330) {
if (triangle_x<0 && triangle_y>0) {
state="left_top";
}else if (triangle_x>0 && triangle_y>0) {
state="right_top";
}else{
alert("卡在:y>=330")
}
}else if (x<=-330) {
if (triangle_x<0 && triangle_y<0) {
state="right_top";
}else if (triangle_x<0 && triangle_y>0) {
state="right_button";
}else{
alert("卡在:x<=-330")
}
}else if (y<=-330) {
if (triangle_x<0 && triangle_y<0) {
state="left_button";
}else if (triangle_x>0 && triangle_y<0) {
state="right_button";
}else{
alert("y<=-330");
}
}
target_x=x;//储存本次x;
target_y=y;//储存本次y;
switch (state){
case "right_button":
x+=high;
y+=low;
break;
case "left_button":
x-=high;
y+=low;
break;
case "right_top":
x+=high;
y-=low;
break;
case "left_top":
x-=high;
y-=low;
break;
}
}
setInterval(action,100);
}