JSFiddle - React, Tailwind, and code Playground

by xianjian

HTML

<div>
<canvas id="can" width="600" height="600" style="float:left">
你的浏览器不支持HTML5 Canvas!
</canvas>
<div style="margin-left:10px;float:left" id="board"></div>
</div>
<div style="clear:both">
<input style="width:50px; padding:3px" id="angle" placeholder="角度" value="100"/>
<button style="width:50px; height:30px;" onclick="drawAngle()">转动</button>
<button style="width:100px; height:30px;" onclick="drawAngleRandom()">角度随机转动</button>
</div>

CSS

body{font:14px 微软雅黑}

JavaScript

function $(o){
  return document.getElementById(o);
}
var can = $('can');
var context = can.getContext('2d');

function draw(angle){
  context.fillStyle="#444";
  context.fillRect(0, 0, 600, 600);
  context.beginPath();
  context.moveTo(300, 0);
  context.lineTo(300,600);
  context.moveTo(0, 300);
  context.lineTo(600,300);
  context.moveTo(290, 20);
  context.lineTo(300,0);
  context.lineTo(310,20);
  context.lineTo(290,20);
  context.moveTo(580, 290);
  context.lineTo(600,300);
  context.lineTo(580,310);
  context.lineTo(580,290);
   context.moveTo(300, 300);
  context.arc(300,300,300,0,2*Math.PI,true);
  context.closePath();
  context.strokeStyle="#fff";
  context.lineWidth=1;
  context.closePath();
  context.stroke();
  context.fillStyle="#FFF";
  context.font="20px Arial";
  context.fillText('X',575,330);
  context.fillText('Y',320,30);
  var arcd = angle*Math.PI/180;
  var x = Math.cos(arcd);
  var y = Math.sin(arcd);
  context.beginPath();
  context.arc(300+x*200,300+y*200,10,0,2*Math.PI,true);
  context.closePath();
  context.fillStyle="#d00";
  context.fill();
  var str = "角度: "+ parseFloat(angle).toFixed(2) +'<br />';
  str += "弧度: "+ arcd.toFixed(2) +'<br />';
  str += "cosX: "+ x.toFixed(2) +'<br />';
  str += "sinY: "+ y.toFixed(2)+'<br />';
  str += "X位置(cosX*200): "+ (x*200).toFixed(2) +'<br />';
  str += "Y位置(sinY*200): "+ (y*200).toFixed(2)+'<br />';
  $('board').innerHTML= str;
}

function drawAngle(){
 draw($('angle').value);
}

function drawAngleRandom(){
  draw(Math.random()*360);
}
drawAngle();